[英]python idiomatic python for loop if else statement
How can I use else
statement in an idiomatic Python for
loop? 如何在惯用的Python
for
循环中使用else
语句? Without else
I can write eg: 没有
else
我可以写例如:
res = [i for i in [1,2,3,4,5] if i < 4]
The result is: [1, 2, 3]
结果是:
[1, 2, 3]
The normal form of the above code is: 上述代码的正常形式是:
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
The result is the same as in idiomatic form: [1, 2, 3]
结果与惯用形式相同:
[1, 2, 3]
And I want this: 我想要这个:
res = [i for i in [1,2,3,4,5] if i < 4 else 0]
I get SyntaxError: invalid syntax
. 我得到
SyntaxError: invalid syntax
。 The result should be: [1, 2, 3, 0, 0]
The normal code of this is: 结果应该是:
[1, 2, 3, 0, 0]
这个的正常代码是:
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
else:
res.append(0)
The result is: [1, 2, 3, 0, 0]
结果是:
[1, 2, 3, 0, 0]
你很接近,你只需要将三元组移动到列表理解中创建值的部分。
res = [i if i < 4 else 0 for i in range(1,6)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.