如果列表中的其他理解 [英] if else in a list comprehension
本文介绍了如果列表中的其他理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个清单 l
:
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
对于45以上的数字包容性,我想加1;对于小于它的数字,5。
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
我试过
[x+1 for x in l if x >= 45 else x+5]
但它给我一个语法错误。如果&ndash,如何实现;
else
在列表推导中是这样的吗?
But it gives me a syntax error. How can I achieve an if
– else
like this in a list comprehension?
推荐答案
>>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in l]
[27, 18, 46, 51, 99, 70, 48, 49, 6]
如果< condition>
,请执行其他操作,否则执行其他操作。
Do-something if <condition>
, else do-something else.
这篇关于如果列表中的其他理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文