首页 > 解决方案 > 在列表中循环 | 蟒蛇 3

问题描述

好吧,我试图理解某个人的代码,关键是他在他的代码中使用了(我猜)很多快捷方式,我无法真正理解他想要做什么以及它是如何工作的。这是一段代码:

scores = [int(scores_temp) for scores_temp in 
          input().strip().split(' ')]

我不明白他在列表中循环?以及他如何定义一个值(scores_temp),然后在 for 中创建它loop

我真的不明白发生了什么以及如何正确阅读

标签: pythonpython-3.xlistloopsshortcut

解决方案


谷歌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]

推荐阅读