0%

python笔记:条件表达式和列表生成式

python 条件表达式(ternary operator):

1
a if b else c

python 列表生成式(List Comprehension):

1
[x for x in range(100) if y]

同时使用条件表达式与列表生成式:

1
[a if {condition of x} else c for x in range(100) (if y) ]

(if y)不是条件表达式中的语法,而是列表生成式的语法(filter)
例子:

1
[1 if x%2==1 else 0 for x in range(10)]

结果:[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
例子2:

1
[1 if x%2==1 else 0 for x in range(10) if x%3==0]

结果:
[0, 1, 0, 1]

source:
https://stackoverflow.com/questions/17321138/one-line-list-comprehension-if-else-variants#comment50313650_17321170
https://stackoverflow.com/questions/2951701/is-it-possible-to-use-else-in-a-list-comprehension