Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用并发循环python进行列表理解_Python_Loops_List Comprehension - Fatal编程技术网

使用并发循环python进行列表理解

使用并发循环python进行列表理解,python,loops,list-comprehension,Python,Loops,List Comprehension,简单的问题,因为我只想写更多的Python代码。我想把下面的内容转换成一个列表 index_row = 0 for row in stake_year.iterrows(): self.assertTrue(row[0] == counts[index_row][0]) self.assertTrue(row[1][0] == counts[index_row][1]) index_row += 1 我不懂的是如何浏览计数表。我不想要嵌套的,例如: [self.asse

简单的问题,因为我只想写更多的Python代码。我想把下面的内容转换成一个列表

index_row = 0
for row in stake_year.iterrows():
    self.assertTrue(row[0] == counts[index_row][0])
    self.assertTrue(row[1][0] == counts[index_row][1])
    index_row += 1
我不懂的是如何浏览计数表。我不想要嵌套的,例如:

[self.assertTrue(x[0] == counts[y][0] for x in stake_year for y in counts]
我现在的代码正在运行,但我希望更好地理解python,并按照应该使用的方式使用该语言。

不要这样做

从定义上讲,列表理解并不比简单循环更像python——只有当这些循环设计用于构建新的列表(或dicts、set等),并且listcomp比循环更容易阅读时

在您的示例中,情况并非如此(您没有构建任何东西),并且您不应该仅针对listcomp的副作用使用它,这显然是非音速的

所以,转换信仰是件好事

result = []
for line in lines:
    result.append(line.upper())
进入


但不是你的例子。

在你的案例中使用的更具python风格的方法是:


在我看来,您想使用
enumerate()
列表理解用于创建列表,而不是执行循环。我想要的是枚举。我不应该称之为列表理解,但这都是学习的一部分。谢谢大家。那么,别忘了接受@minitoto的回答。:)我假设
.assertTrue
返回
None
,因此您不想要的列表comp将创建一个包含
None
的列表,您将立即丢弃该列表。这样做是非常不符合Python的,在普通代码中没有位置。。。但人们有时在编码高尔夫和其他奇怪的编码游戏中也会做类似的事情谢谢你的评论,蒂姆,我是一只老恐龙,学习python很开心,这段旅程真的很有趣。我一直在尝试编写汇编程序,但这并不总是python中最好的方法:)这是完美的,枚举现在是有意义的。谢谢@minitoto。
result = [line.upper() for line in lines]
for index_row, row in enumerate(stake_year.iterrows()):
    self.assertTrue(row[0] == counts[index_row][0])
    self.assertTrue(row[1][0] == counts[index_row][1])