python idiomatic python for loop if else statement

给你一囗甜甜゛ 提交于 2019-12-04 00:57:48

问题


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)] 


来源:https://stackoverflow.com/questions/33678809/python-idiomatic-python-for-loop-if-else-statement

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