Python 单行列表理解:if-else 变体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17321138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:53:14  来源:igfitidea点击:

One-line list comprehension: if-else variants

pythonlist-comprehensionternary-operatorconditional-operator

提问by ducin

It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range:

更多的是关于python列表理解语法。我有一个列表理解,可以生成给定范围的奇数列表:

[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:

这构成了一个过滤器 - 我有一个源列表,我在其中删除了偶数 ( 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

There is a python expression like if-else:

有一个像 if-else 这样的 python 表达式:

1 if 0 is 0 else 3

How to use it inside a list comprehension?

如何在列表理解中使用它?

采纳答案by shx2

x if y else zis the syntax for the expression you're returning for each element. Thus you need:

x if y else z是您为每个元素返回的表达式的语法。因此你需要:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filterin the first example, but not in the second. In the second example you're only mappingeach 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.

在你的第二个例子中,表达式是一个“复杂”的表达式,它恰好涉及一个if-else.

回答by lucasg

[x if x % 2 else x * 100 for x in range(1, 10) ]

回答by James Sapam

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]
>>>

回答by Stefan Gruenwald

You can do that with list comprehension too:

您也可以使用列表理解来做到这一点:

A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A

回答by anudeep

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]
>>>