如何在python中以什么顺序评估列表推导 [英] How list comprehensions are evaluated in python and in what order

查看:37
本文介绍了如何在python中以什么顺序评估列表推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表推导,其中在不同位置定义了条件.

I have two list comprehensions where conditions are defined in different places.

>>> [ x**2 if x%2==0 else x**3 if x%3==0 else 0 for x in range(10)]
[0, 0, 4, 27, 16, 0, 36, 0, 64, 729]

>>> [ x**2 if x%2==0 for x in range(10) ]
  File "<stdin>", line 1
    [ x**2 if x%2==0 for x in range(10) ]
                       ^
SyntaxError: invalid syntax

但是,如果我这样做:

>>> [ x**2 for x in range(10) if x%2==0 ]
[0, 4, 16, 36, 64]
>>> 

有效.

现在,令人困惑的部分是如何评估订单.有什么区别?

Now the confusing part is how the order is evaluated. What is the difference?

推荐答案

您在这里有两个不同的概念.

You have two different concepts confused here.

x**2 if x%2==0 else x**3之类的表达式是条件表达式.它们可以被链接,但是else非可选的-因为这是一个自包含表达式,计算得出的是单个特定值. else x**3是必需的,因为无论何时x % 2 == 0都不是Python,Python都必须知道表达式的计算结果.

An expression like x**2 if x%2==0 else x**3 is a conditional expression. They can be chained, but the else is not optional - because this is a self-contained expression that evaluates to a single, specific value. The else x**3 is required because Python has to know what the expression evaluates to whenever it is not the case that x % 2 == 0.

列表理解中,当您编写[x**2 for x in range(10) if x%2==0]之类的内容时,if子句用于过滤 in range(10)中找到的x值, for计算结果列表中的哪些元素.此处不允许else,因为目的是完全不同的.

In a list comprehension, when you write things like [x**2 for x in range(10) if x%2==0], the if clause is used to filter the x values found in range(10), for which elements of the resulting list are computed. There is no else permitted here because the purpose is entirely different.

您可以混合搭配:[x**2 if x%2 == 0 else x**3 for x in range(10) if x%3 == 0].现在,使用if x % 3 == 0决定要为其计算结果的x值,并且使用if x%2 == 0决定是否使用x**2x**3作为计算结果对于那些x.

You can mix and match: [x**2 if x%2 == 0 else x**3 for x in range(10) if x%3 == 0]. Now if x % 3 == 0 is being used to decide which x values to compute a result for, and if x%2 == 0 is being used to decide whether to use x**2 or x**3 as the computed result for those xs.

这篇关于如何在python中以什么顺序评估列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆