【问题标题】:loop right in the list | python 3在列表中循环 |蟒蛇 3
【发布时间】:2020-06-21 17:32:51
【问题描述】:

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

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

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

我真的不明白发生了什么,我怎么才能正确地阅读这个

【问题讨论】:

标签: python python-3.x list loops shortcut


【解决方案1】:

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]

【讨论】:

  • 当您熟悉 python dictionariesgenerators 后,您也可以使用类似的语法。不仅仅是列表
【解决方案2】:

这称为list comprehension。它是创建列表的快捷方式。 和这段代码一样:

result = []
for scores_tempo in input().strip().split():
    result.append(int(scores_temp)

因为您需要创建列表、字典、集合等。python 通常对此有特殊的快捷语法。也称为语法糖

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-06
    • 2018-03-28
    • 2018-06-17
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多