清单理解条件中的`elif` [英] `elif` in list comprehension conditionals
本文介绍了清单理解条件中的`elif`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以在列表理解中使用elif
吗?
Can we use elif
in list comprehension?
示例:
l = [1, 2, 3, 4, 5]
for values in l:
if values==1:
print 'yes'
elif values==2:
print 'no'
else:
print 'idle'
我们可以像上面的代码一样将elif
包括在列表推导中吗?
Can we include the elif
in our list comprehension, in a similar fashion to the code above?
例如,答案如下:
['yes', 'no', 'idle', 'idle', 'idle']
到目前为止,我只在列表理解中使用了if
和else
.
Up until now, I have only used if
and else
in list comprehension.
推荐答案
Python的条件表达式正是针对这种用例而设计的:
Python's conditional expressions were designed exactly for this sort of use-case:
>>> 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']
希望这会有所帮助:-)
Hope this helps :-)
这篇关于清单理解条件中的`elif`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文