问题:单行列表理解:if-else变体
更多有关python列表理解语法的信息。我有一个列表推导,它产生给定范围的奇数列表:
[x for x in range(1, 10) if x % 2]
这将构成一个过滤器-我有一个源列表,其中删除了偶数(if x % 2
)。我想在这里使用if-then-else之类的东西。以下代码失败:
>>> [x for x in range(1, 10) if x % 2 else x * 100]
File "<stdin>", line 1
[x for x in range(1, 10) if x % 2 else x * 100]
^
SyntaxError: invalid syntax
有一个类似if-else的python表达式:
1 if 0 is 0 else 3
如何在列表理解中使用它?
It’s more about python list comprehension syntax. I’ve got a list comprehension that produces list of odd numbers of a given range:
[x for x in range(1, 10) if x % 2]
This makes a filter – I’ve got a source list, where I remove even numbers (if x % 2
). I’d like to use something like if-then-else here. Following code fails:
>>> [x for x in range(1, 10) if x % 2 else x * 100]
File "<stdin>", line 1
[x for x in range(1, 10) if x % 2 else x * 100]
^
SyntaxError: invalid syntax
There is a python expression like if-else:
1 if 0 is 0 else 3
How to use it inside a list comprehension?
回答 0
x if y else z
是您要为每个元素返回的表达式的语法。因此,您需要:
[ x if x%2 else x*100 for x in range(1, 10) ]
混淆是由于您在第一个示例中使用了过滤器而在第二个示例中没有使用过滤器。在第二个示例中,您仅映射使用三元运算符表达式每个值到另一个。
使用过滤器,您需要:
[ EXP for x in seq if COND ]
没有过滤器,您需要:
[ EXP for x in seq ]
在第二个示例中,该表达式是一个“复杂”表达式,其中恰好包含一个if-else
。
x if y else z
is the syntax for the expression you’re returning for each element. Thus you need:
[ x if x%2 else x*100 for x in range(1, 10) ]
The confusion arises from the fact you’re using a filter in the first example, but not in the second. In the second example you’re only mapping each value to another, using a ternary-operator expression.
With a filter, you need:
[ EXP for x in seq if COND ]
Without a filter you need:
[ EXP for x in seq ]
and in your second example, the expression is a “complex” one, which happens to involve an if-else
.
回答 1
[x if x % 2 else x * 100 for x in range(1, 10) ]
[x if x % 2 else x * 100 for x in range(1, 10) ]
回答 2
您也可以使用列表理解来做到这一点:
A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A
You can do that with list comprehension too:
A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A
回答 3
只是另一种解决方案,希望有人会喜欢它:
使用:[假,真] [表达式]
>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
Just another solution, hope some one may like it :
Using: [False, True][Expression]
>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
回答 4
我能够做到这一点
>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
I was able to do this
>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>