我有一个清单xs
包含字符串的混合物和None
价值观。如何使用列表理解在每个字符串上调用函数,但将None
价值观''
(而不是将它们传递给函数)?
I tried:
[f(x) for x in xs if x is not None else '']
但它给出了SyntaxError
。正确的语法是什么?
See List comprehension with condition https://stackoverflow.com/questions/24442091 if you are trying to make a list comprehension that omits values based on a condition.
If you need to consider more than two conditional outcomes, beware that Python's conditional expressions https://stackoverflow.com/questions/394809/ do not support elif
. Instead, it is necessary to nest if
/else
conditionals. See `elif` in list comprehension conditionals https://stackoverflow.com/questions/9987483 for details.
你完全可以做到这一点。这只是一个顺序问题:
[f(x) if x is not None else '' for x in xs]
一般来说,
[f(x) if condition else g(x) for x in sequence]
并且,对于列表理解if
仅条件,
[f(x) for x in sequence if condition]
请注意,这实际上使用了不同的语言构造,条件表达式 https://docs.python.org/3/reference/expressions.html#conditional-expressions,它本身不属于理解语法 https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries,而if
之后for…in
是列表推导式的一部分,用于filter来自可迭代源的元素。
条件表达式可用于您想要根据某些条件在两个表达式值之间进行选择的各种情况。这与三元运算符?:存在于其他语言中 https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator。例如:
value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)