python - 在列表中循环 | 蟒蛇 3
问题描述
好吧,我试图理解某个人的代码,关键是他在他的代码中使用了(我猜)很多快捷方式,我无法真正理解他想要做什么以及它是如何工作的。这是一段代码:
scores = [int(scores_temp) for scores_temp in
input().strip().split(' ')]
我不明白他在列表中循环?以及他如何定义一个值(scores_temp)
,然后在 for 中创建它loop
。
我真的不明白发生了什么以及如何正确阅读
解决方案
谷歌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]
推荐阅读
- sql - 根据另一个表中的值过滤表的行(Oracle)
- docker - Docker 卷安装问题到已安装的文件夹
- postgresql - 如何在postgresql中分隔逗号分隔值字符串并逐行保存
- c++ - 如何在 C++ 中找到数组的大小?
- deep-learning - 最多使用第 n 个时间步的 RNN (LSTM)
- python - 如果单词在 Python 的两列中,则从两列中删除列表中的单词
- php - 如何在 Laravel 中使用 ajax 请求插入 sessionStorage 数据?
- pine-script - 使用带有赋值的布尔值计算透明度时出错?
- contiki - Contiki:如何在不同的 RPL 目标函数之间切换?
- python - 写入 postgresql 数据库表或 csv 文件?哪个更快?