python idiomatic python for loop if else statement

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

How can I use 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]

The result is: [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]

And I want this:

res = [i for i in [1,2,3,4,5] if i < 4 else 0]

I get 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)

The result is: [1, 2, 3, 0, 0]

回答1:

You were close, you just have to move the ternary to the part of the list comprehension where you're creating the value.

res = [i if i < 4 else 0 for i in range(1,6)] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!