python-3.x int(n)for n是什么意思

2exbekwf  于 2023-05-19  发布在  Python
关注(0)|答案(3)|浏览(155)

为了将输入放入列表中:

numbersList = [int(n) for n in input('Enter numbers: ').split()]

有人能解释一下int(n)for n in是什么意思吗?
如何改进此问题?

lqfhib0f

lqfhib0f1#

整个表达式称为列表解析。这是一种更简单的Python方法,可以构造一个遍历列表的for循环。
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
给定您的代码:

numbersList = [int(n) for n in input('Enter numbers: ').split()]

假设你运行提供的代码,你会得到一个输入提示:

Enter numbers: 10 8 25 33

现在发生的是,Python的input()函数返回一个字符串,如下所示:
https://docs.python.org/3/library/functions.html#input
所以代码现在基本上变成了这样:

numbersList = [int(n) for n in "10 8 25 33".split()]

现在,split()函数返回一个由给定字符分隔的字符串中的元素组成的数组,作为字符串。
https://www.pythonforbeginners.com/dictionary/python-split
现在你的代码变成了:

numbersList = [int(n) for n in ["10", "8", "25", "33"]]

这段代码现在相当于:

numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
    numberList.append(int(n))

int(n)方法将参数n从字符串转换为int并返回int。
https://docs.python.org/3/library/functions.html#int

hwamh0ep

hwamh0ep2#

例如,input('Enter numbers: ').split()返回一个字符串数组,如['1', '4', '5']
int(n) for n in将遍历数组,并将每个n转换为整数,而n将是数组的相应项。

vc9ivgsu

vc9ivgsu3#

让我们试着通过一段简单的代码来理解这个 *list compensation * 表达式,这段代码的意思是相同的。

nums = input('Enter numbers: ') # suppose 5 1 3 6 

nums = nums.split() # it turns it to ['5', '1', '3', '6']

numbersList = [] # this is list in which the expression is written

for n in nums: # this will iterate in the nums.
    number = int(n) # number will be converted from '5' to 5
    numbersList.append(number) # add it to the list

print(numbersList) # [5, 1, 3, 6]

相关问题