为了将输入内容放入列表中:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
有人可以解释“ int(n)for n in”是什么意思吗?
答案 0 :(得分:3)
整个表达式称为列表理解。这是一种构造循环遍历列表的for循环的更简单的Pythonic方法。
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。
答案 1 :(得分:2)
例如,input('Enter numbers: ').split()
返回一个字符串数组,例如['1', '4', '5']
int(n) for n in
将遍历数组并将每个n
转换为整数,而n
将是数组的相应项。
答案 2 :(得分:1)
通过一段简单的代码,让我们尝试理解这个 list理解表达式。
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]