You can totally do that, it's just an ordering issue:
(您可以完全做到这一点,这只是订购问题:)
[unicode(x.strip()) if x is not None else '' for x in row]
In general,
(一般来说,)
[f(x) if condition else g(x) for x in sequence]
And, for list comprehensions with if
conditions only,
(而且,与列表内涵if
只是条件,)
[f(x) for x in sequence if condition]
Note that this actually uses a different language construct, a conditional expression , which itself is not part of the comprehension syntax , while the if
after the for…in
is part of list comprehensions and used to filter elements from the source iterable.
(请注意,这实际上使用了一种不同的语言构造,即条件表达式 ,它本身不是理解语法的一部分,而for…in
之后的if
是列表理解的一部分,用于从可迭代的源中筛选元素。)
Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition.
(条件表达式可用于要根据条件在两个表达式值之间进行选择的所有情况。)
This does the same as the ternary operator ?:
that exists in other languages . (这与其他语言中存在的三元运算符?:
相同。)
For example: (例如:)
value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…