Python list 生成式(推导式list comprehe

2017-12-02  本文已影响443人  dawsongzhao

在list生成式中嵌套if else

如果按中文习惯写嵌套列表生成式可能写出如下的错误语法

>>> [x for x in range(1, 10) if x % 2 else x * 100]
  File "<stdin>", line 1
    [x for x in range(1, 10) if x % 2 else x * 100]
                                         ^
SyntaxError: invalid syntax

Python的语法是按英文阅读方式设计的,因此,正常的方式应该是

>>> [ x if x%2 else x*100 for x in range(1, 10) ]
[1, 200, 3, 400, 5, 600, 7, 800, 9]

或者用更简洁的形式[false,true][condition] is the syntax

>>> [[x*100,x][x %2] for x in range(1,10)]
[1, 200, 3, 400, 5, 600, 7, 800, 9]

更多阅读

通过示例学习Python列表推导
if/else in Python's list comprehension?
python one-line list comprehension: if-else variants
if else in a list comprehension [duplicate]

上一篇下一篇

猜你喜欢

热点阅读