Google python 列表理解,你会得到大量与此相关的材料。查看给定的代码,我猜输入类似于" 1 2 3 4 5 "。您在[] 中所做的是运行for 循环并使用循环变量在一个简单的行中创建一个列表
让我们分解代码。假设输入是" 1 2 3 4 5 "
input().strip() # Strips leading and trailing spaces
>>> "1 2 3 4 5"
input().strip().split() # Splits the string by spaces and creates a list
>>> ["1", "2", "3", "4", "5"]
现在是 for 循环;
for scores_temp in input().strip().split(' ')
现在等于
for scores_temp in ["1", "2", "3", "4", "5"]
现在scores_temp 在每次循环迭代中将等于"1", "2", "3"...。你想使用变量scores_temp 来创建一个循环,通常你会这样做,
scores = []
for scores_temp in ["1", "2", "3", "4", "5"]:
scores.append(int(scores_temp)) # Convert the number string to an int
除了上面的 3 行之外,在 python 中,您可以使用列表推导在一行中完成此操作。这就是[int(scores_temp) for scores_temp in input().strip().split(' ')]。
这是python中一个非常强大的工具。您甚至可以在[] 中使用 if 条件、更多 for 循环 ...等
例如10以内的偶数列表
[i for i in range(10) if i%2==0]
>>> [0, 2, 4, 6, 8]
扁平化列表列表
[k for j in [[1,2], [3,4]] for k in j]
>>> [1, 2, 3, 4]