是否可以使用“else”?在列表理解中?

发布于 2024-09-04 11:59:02 字数 318 浏览 3 评论 0原文

这是我试图转换为列表理解的代码:

table = ''
for index in xrange(256):
    if index in ords_to_keep:
        table += chr(index)
    else:
        table += replace_with

有没有办法将 else 语句添加到此理解中?

table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)

Here is the code I was trying to turn into a list comprehension:

table = ''
for index in xrange(256):
    if index in ords_to_keep:
        table += chr(index)
    else:
        table += replace_with

Is there a way to add the else statement to this comprehension?

table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

梦里寻她 2024-09-11 11:59:02

语法 a if b else c 是 Python 中的三元运算符,如果条件 b 为真,则计算结果为 a - 否则,计算结果为c.它可以用在理解语句中:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

所以对于你的例子,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))
晨曦÷微暖 2024-09-11 11:59:02

要在 Python 编程中的列表推导中使用 else,您可以尝试以下代码片段。这将解决您的问题,该代码片段在 python 2.7 和 python 3.5 上进行了测试。

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]

To use the else in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
千柳 2024-09-11 11:59:02

如果您想要一个else,您不想过滤列表理解,您希望它迭代每个值。您可以使用 true-value if cond else false-value 作为语句,并从末尾删除过滤器:

table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))

If you want an else you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value as the statement instead, and remove the filter from the end:

table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
小伙你站住 2024-09-11 11:59:02

else可以在Python中使用列表 带有 的理解 条件表达式(“三元运算符”):

>>> [("A" if b=="e" else "c") for b in "comprehension"]
['c', 'c', 'c', 'c', 'c', 'A', 'c', 'A', 'c', 'c', 'c', 'c', 'c']

这里的括号“()”只是为了强调条件表达式,不一定是必需的(运算符优先级)。

此外,可以嵌套多个表达式,从而导致更多的 else 和难以阅读的代码:

>>> ["A" if b=="e" else "d" if True else "x" for b in "comprehension"]
['d', 'd', 'd', 'd', 'd', 'A', 'd', 'A', 'd', 'd', 'd', 'd', 'd']
>>>

在相关说明中,推导式还可以包含自己的 if 条件最后:

>>> ["A" if b=="e" else "c" for b in "comprehension" if False]
[]
>>> ["A" if b=="e" else "c" for b in "comprehension" if "comprehension".index(b)%2]
['c', 'c', 'A', 'A', 'c', 'c']

条件s?是的,多个 if 是可能的,实际上也可以有多个 for:(

>>> [i for i in range(3) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
>>> [i for i in range(3) if i for _ in range(3) if _ if True if True]
[1, 1, 2, 2]

单个下划线 _ 是一个有效的变量名称(标识符),此处使用只是为了表明它实际上并未使用它在交互中具有特殊含义。模式)

将其用于附加条件表达式是可能的,但没有实际用途:

>>> [i for i in range(3)]
[0, 1, 2]
>>> [i for i in range(3) if i]
[1, 2]
>>> [i for i in range(3) if (True if i else False)]
[1, 2]

推导式也可以嵌套来创建“多维”列表(“数组”):

>>> [[i for j in range(i)] for i in range(3)]
[[], [1], [2, 2]]

最后但并非最不重要的一点是,推导式不是仅限于创建 list,即 elseif 也可以在 set 理解:

>>> {i for i in "set comprehension"}
{'o', 'p', 'm', 'n', 'c', 'r', 'i', 't', 'h', 'e', 's', ' '}

字典 理解:

>>> {k:v for k,v in [("key","value"), ("dict","comprehension")]}
{'key': 'value', 'dict': 'comprehension'}

相同的语法也用于 < a href="https://docs.python.org/3/reference/expressions.html#generator-expressions" rel="noreferrer">生成器表达式:

>>> for g in ("a" if b else "c" for b in "generator"):
...     print(g, end="")
...
aaaaaaaaa>>>

可用于创建元组 (没有元组理解)。


Further reading:

Yes, else can be used in Python inside a list comprehension with a Conditional Expression ("ternary operator"):

>>> [("A" if b=="e" else "c") for b in "comprehension"]
['c', 'c', 'c', 'c', 'c', 'A', 'c', 'A', 'c', 'c', 'c', 'c', 'c']

Here, the parentheses "()" are just to emphasize the conditional expression, they are not necessarily required (Operator precedence).

Additionaly, several expressions can be nested, resulting in more elses and harder to read code:

>>> ["A" if b=="e" else "d" if True else "x" for b in "comprehension"]
['d', 'd', 'd', 'd', 'd', 'A', 'd', 'A', 'd', 'd', 'd', 'd', 'd']
>>>

On a related note, a comprehension can also contain its own if condition(s) at the end:

>>> ["A" if b=="e" else "c" for b in "comprehension" if False]
[]
>>> ["A" if b=="e" else "c" for b in "comprehension" if "comprehension".index(b)%2]
['c', 'c', 'A', 'A', 'c', 'c']

Conditions? Yes, multiple ifs are possible, and actually multiple fors, too:

>>> [i for i in range(3) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
>>> [i for i in range(3) if i for _ in range(3) if _ if True if True]
[1, 1, 2, 2]

(The single underscore _ is a valid variable name (identifier) in Python, used here just to show it's not actually used. It has a special meaning in interactive mode)

Using this for an additional conditional expression is possible, but of no real use:

>>> [i for i in range(3)]
[0, 1, 2]
>>> [i for i in range(3) if i]
[1, 2]
>>> [i for i in range(3) if (True if i else False)]
[1, 2]

Comprehensions can also be nested to create "multi-dimensional" lists ("arrays"):

>>> [[i for j in range(i)] for i in range(3)]
[[], [1], [2, 2]]

Last but not least, a comprehension is not limited to creating a list, i.e. else and if can also be used the same way in a set comprehension:

>>> {i for i in "set comprehension"}
{'o', 'p', 'm', 'n', 'c', 'r', 'i', 't', 'h', 'e', 's', ' '}

and a dictionary comprehension:

>>> {k:v for k,v in [("key","value"), ("dict","comprehension")]}
{'key': 'value', 'dict': 'comprehension'}

The same syntax is also used for Generator Expressions:

>>> for g in ("a" if b else "c" for b in "generator"):
...     print(g, end="")
...
aaaaaaaaa>>>

which can be used to create a tuple (there is no tuple comprehension).


Further reading:

一直在等你来 2024-09-11 11:59:02

另外,我的结论是列表理解是最有效的方法吗?

或许。列表推导式本质上计算效率并不高。它仍然以线性时间运行。

从我个人的经验来看:
通过用上面的 for 循环/列表附加类型结构替换列表推导式(特别是嵌套推导式),我在处理大型数据集时显着减少了计算时间。在此应用程序中,我怀疑您会注意到差异。

Also, would I be right in concluding that a list comprehension is the most efficient way to do this?

Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.

From my personal experience:
I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.

土豪我们做朋友吧 2024-09-11 11:59:02

很好的答案,但只是想提一个问题,即“pass”关键字在列表理解的 if/else 部分中不起作用(如上面提到的示例中发布的)。

#works
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else x**2 for x in list1 ]
print(newlist2, type(newlist2))

#but this WONT work
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else pass for x in list1 ]
print(newlist2, type(newlist2))

这是在 python 3.4 上尝试和测试的。
错误如下:

newlist2 = [x if x > 30 else pass for x in list1 ]                                    
SyntaxError: invalid syntax

因此,尽量避免列表推导中的 pass-es

Great answers, but just wanted to mention a gotcha that "pass" keyword will not work in the if/else part of the list-comprehension (as posted in the examples mentioned above).

#works
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else x**2 for x in list1 ]
print(newlist2, type(newlist2))

#but this WONT work
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else pass for x in list1 ]
print(newlist2, type(newlist2))

This is tried and tested on python 3.4.
Error is as below:

newlist2 = [x if x > 30 else pass for x in list1 ]                                    
SyntaxError: invalid syntax

So, try to avoid pass-es in list comprehensions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文