python惯用python for循环if else语句 [英] python idiomatic python for loop if else statement
问题描述
如何在循环中使用惯用Python 中的
else
语句?没有 else
我可以编写例如:
res = [i for i在[1,2,3,4,5]中,如果i < 4]
结果是: 上面代码的正常形式是: 结果与习惯形式: 我想要: 我得到 结果是: 您很接近,您只需要将三元组移动到您创建值的列表理解部分。 How can I use The result is: The normal form of the above code is: The result is the same as in idiomatic form: And I want this: I get The result is: You were close, you just have to move the ternary to the part of the list comprehension where you're creating the value.
这篇关于python惯用python for循环if else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! [1,2,3]
$ b
res = []
for i in [1,2,3,4,5]:
if i< 4:
res.append(i)
[1,2,3]
res = [i for i in [1,2,3,4,5] if i< 4 else 0]
SyntaxError:invalid syntax
。结果应该是: [1,2,3,0,0]
这是正常的代码:
res = []
for i in [1,2,3,4,5]:
if i< 4:
res.append(i)
else:
res.append(0)
[1,2,3,0,0]
res = [i if i< 4 else 0 for i in range(1,6)]
else
statement in an idiomatic Python for
loop? Without else
I can write e.g.:res = [i for i in [1,2,3,4,5] if i < 4]
[1, 2, 3]
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
[1, 2, 3]
res = [i for i in [1,2,3,4,5] if i < 4 else 0]
SyntaxError: invalid syntax
. The result should be: [1, 2, 3, 0, 0]
The normal code of this is:res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
else:
res.append(0)
[1, 2, 3, 0, 0]
res = [i if i < 4 else 0 for i in range(1,6)]