列出具有多个条件的理解(python) [英] list comprehension with multiple conditions (python)
问题描述
以下代码在Python中有效
The following code works in Python
var=range(20)
var_even = [0 if x%2==0 else x for x in var]
print var,var_even
但是,我认为条件必须放在列表的末尾.如果我编写代码
However, I thought that the conditions need to be put in the end of a list. If I make the code
var_even = [0 if x%2==0 for x in var]
然后它将不起作用.有这个原因吗?
Then it won't work. Is there a reason for this?
推荐答案
这里涉及两种截然不同但外观相似的语法,条件表达式和列表理解过滤器子句
There are two distinct but similar-looking syntaxes involved here, conditional expressions and list comprehension filter clauses.
条件表达式的格式为x if y else z
.此语法与列表推导无关.如果您想在列表理解中有条件地包含一件事或另一件事,那么您将使用以下方法:
A conditional expression is of the form x if y else z
. This syntax isn't related to list comprehensions. If you want to conditionally include one thing or a different thing in a list comprehension, this is what you would use:
var_even = [x if x%2==0 else 'odd' for x in var]
# ^ "if" over here for "this or that"
列表理解过滤子句是elem for x in y if thing
中的if thing
.这是列表理解语法的一部分,并且在for
子句之后.如果要在列表理解中有条件地包括或不包括元素,则可以使用以下方法:
A list comprehension filter clause is the if thing
in elem for x in y if thing
. This is part of the list comprehension syntax, and it goes after the for
clause. If you want to conditionally include or not include an element in a list comprehension, this is what you would use:
var_even = [x for x in var if x%2==0]
# ^ "if" over here for "this or nothing"
这篇关于列出具有多个条件的理解(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!