python - 列表理解条件中的 `elif`

标签 python list-comprehension conditional-operator

我们可以在列表理解中使用 elif 吗?

例子:

l = [1, 2, 3, 4, 5]

for values in l:
    if values==1:
        print 'yes'
    elif values==2:
        print 'no'
    else:
        print 'idle'

我们可以在列表理解中包含 elif,以类似于上面的代码的方式吗?

例如,这样的答案:

['yes', 'no', 'idle', 'idle', 'idle']

到目前为止,我只在列表理解中使用了 ifelse

最佳答案

Python 的 conditional expressions正是为这种用例设计的:

>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']

关于python - 列表理解条件中的 `elif`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9987483/

相关文章:

python - 如何仅更改第一个 "Column name"pandas 的字体

python - 根据条件更改 pandas 中的列值

python - 为什么 itertools.chain 比展平列表理解更快?

python - 在没有列表理解的情况下在 Python 中提取包含字符串的列表项?

c# - 为什么我们更喜欢?至 ?? c#中的运算符?

python - Flask + Wsgi + Docker - 尚未安装用户加载程序

python - lxml - 查找具有特定扩展名的所有链接

Python 使用 takewhile 将 for/while 转换为列表理解

swift - 我如何使用? : in Swift?

javascript - 使用条件运算符检查某些值并将其转换为数字