if else 在列表理解中 [英] if else in a list comprehension
本文介绍了if else 在列表理解中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表 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]
但它给了我一个语法错误.如何实现 if
–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]
如果
做某事,否则做其他事.
Do-something if <condition>
, else do-something else.
这篇关于if else 在列表理解中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文