本文翻译自:if else in a list comprehension [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- if/else in a list comprehension? if / else在列表理解中? 8 answers 8个答案
I have a list l
: 我有一个清单l
:
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
For numbers above 45 inclusive, I would like to add 1; 对于45以上的数字,我想加1; and for numbers less than it, 5. 对于小于它的数字,5。
I tried 我试过了
[x+1 for x in l if x >= 45 else x+5]
But it gives me a syntax error. 但它给了我一个语法错误。 How can I achieve an if
– else
like this in a list comprehension? 我怎样才能在列表理解中实现if
- else
这样的呢?
#1楼
参考:https://stackoom.com/question/IUIn/如果列表中的其他理解-重复
#2楼
You can also put the conditional expression in brackets inside the list comprehension: 您还可以将条件表达式放在列表解析中的括号中:
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
print [[x+5,x+1][x >= 45] for x in l]
[false,true][condition] is the syntax [false,true] [条件]是语法
#3楼
I just had a similar problem, and found this question and the answers really useful. 我刚遇到类似的问题,发现这个问题和答案真的很有用。 Here's the part I was confused about. 这是我感到困惑的部分。 I'm writing it explicitly because no one actually stated it simply in English: 我是明确写的,因为没有人用英语简单地说出来:
The iteration goes at the end. 迭代结束了。
Normally, a loop goes 通常,循环进行
for this many times:
if conditional:
do this thing
else:
do something else
Everyone states the list comprehension part simply as the first answer did, 每个人都将列表理解部分简单地称为第一个答案,
[ expression for item in list if conditional ]
but that's actually not what you do in this case. 但这实际上不是你在这种情况下做的事情。 (I was trying to do it that way) (我试图这样做)
In this case, it's more like this: 在这种情况下,它更像是这样的:
[ expression if conditional else other thing for this many times ]
#4楼
Like in [a if condition1 else b for i in list1 if condition2]
, the two if
s with condition1
and condition2
doing two different things. 就像在[a if condition1 else b for i in list1 if condition2]
,两个if
with condition1
和condition2
做两个不同的事情。 The part (a if condition1 else b)
is from a lambda expression: 部分(a if condition1 else b)
来自lambda表达式:
lambda x: a if condition1 else b
while the other condition2
is another lambda: 而另一个condition2
是另一个lambda:
lambda x: condition2
Whole list comprehension can be regard as combination of map
and filter
: 整个列表理解可以视为map
和filter
组合:
map(lambda x: a if condition1 else b, filter(lambda x: condition2, list1))
#5楼
您必须将表达式放在列表推导的开头,结尾处的if语句过滤元素!
[x+1 if x >= 45 else x+5 for x in l]
#6楼
>>> 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. 如果<condition>
那么做,否则做其他事情。