列表综合句法句法含量为`列表(发电机表达式)`python 3中



在python 3中,列表理解是简单的句法糖,用于发电机表达式中送入list函数的句法?

例如。是以下代码:

squares = [x**2 for x in range(1000)]

实际在后台转换为以下?

squares = list(x**2 for x in range(1000))

我知道输出是相同的,Python 3将令人惊讶的副作用固定在列表综合的周围名称空间上的令人惊讶的副作用,但是就CPYTHON解释器所做的事情而言,前者是前者转换为后者的,或代码如何执行有什么区别?

背景

我在此问题的评论部分中发现了这一对等价的主张,并且快速的Google搜索显示了此处的同样主张。

在python 3.0文档中的新事物中也提到了这一点,但是措辞有些模糊:

还要注意,列表综合具有不同的语义:它们更接近列表()构造函数中的发电机表达式的句法糖,尤其是循环控制变量不再泄漏到周围的范围中。

两者的工作方式不同。列表理解版本利用了特殊字节码LIST_APPEND,它直接为我们调用PyList_Append。因此,它避免了属性查找到 list.append,并在python级别进行调用。

>>> def func_lc():
    [x**2 for x in y]
...
>>> dis.dis(func_lc)
  2           0 LOAD_CONST               1 (<code object <listcomp> at 0x10d3c6780, file "<ipython-input-42-ead395105775>", line 2>)
              3 LOAD_CONST               2 ('func_lc.<locals>.<listcomp>')
              6 MAKE_FUNCTION            0
              9 LOAD_GLOBAL              0 (y)
             12 GET_ITER
             13 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             16 POP_TOP
             17 LOAD_CONST               0 (None)
             20 RETURN_VALUE
>>> lc_object = list(dis.get_instructions(func_lc))[0].argval
>>> lc_object
<code object <listcomp> at 0x10d3c6780, file "<ipython-input-42-ead395105775>", line 2>
>>> dis.dis(lc_object)
  2           0 BUILD_LIST               0
              3 LOAD_FAST                0 (.0)
        >>    6 FOR_ITER                16 (to 25)
              9 STORE_FAST               1 (x)
             12 LOAD_FAST                1 (x)
             15 LOAD_CONST               0 (2)
             18 BINARY_POWER
             19 LIST_APPEND              2
             22 JUMP_ABSOLUTE            6
        >>   25 RETURN_VALUE

另一方面,list()版本只需将生成器对象传递到列表的__init__方法,然后在内部调用其extend方法。由于对象不是列表或元组,因此Cpython首先获取其迭代器,然后简单地将项目添加到列表中,直到迭代器用尽:

>>> def func_ge():
    list(x**2 for x in y)
...
>>> dis.dis(func_ge)
  2           0 LOAD_GLOBAL              0 (list)
              3 LOAD_CONST               1 (<code object <genexpr> at 0x10cde6ae0, file "<ipython-input-41-f9a53483f10a>", line 2>)
              6 LOAD_CONST               2 ('func_ge.<locals>.<genexpr>')
              9 MAKE_FUNCTION            0
             12 LOAD_GLOBAL              1 (y)
             15 GET_ITER
             16 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             19 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             22 POP_TOP
             23 LOAD_CONST               0 (None)
             26 RETURN_VALUE
>>> ge_object = list(dis.get_instructions(func_ge))[1].argval
>>> ge_object
<code object <genexpr> at 0x10cde6ae0, file "<ipython-input-41-f9a53483f10a>", line 2>
>>> dis.dis(ge_object)
  2           0 LOAD_FAST                0 (.0)
        >>    3 FOR_ITER                15 (to 21)
              6 STORE_FAST               1 (x)
              9 LOAD_FAST                1 (x)
             12 LOAD_CONST               0 (2)
             15 BINARY_POWER
             16 YIELD_VALUE
             17 POP_TOP
             18 JUMP_ABSOLUTE            3
        >>   21 LOAD_CONST               1 (None)
             24 RETURN_VALUE
>>>

计时比较:

>>> %timeit [x**2 for x in range(10**6)]
1 loops, best of 3: 453 ms per loop
>>> %timeit list(x**2 for x in range(10**6))
1 loops, best of 3: 478 ms per loop
>>> %%timeit
out = []
for x in range(10**6):
    out.append(x**2)
...
1 loops, best of 3: 510 ms per loop

由于属性缓慢查找,正常循环略有缓慢。再次缓存和时间。

>>> %%timeit
out = [];append=out.append
for x in range(10**6):
    append(x**2)
...
1 loops, best of 3: 467 ms per loop

除了列表理解不再泄漏变量的事实外,还有一个区别是,类似变量已不再有效:

>>> [x**2 for x in 1, 2, 3] # Python 2
[1, 4, 9]
>>> [x**2 for x in 1, 2, 3] # Python 3
  File "<ipython-input-69-bea9540dd1d6>", line 1
    [x**2 for x in 1, 2, 3]
                    ^
SyntaxError: invalid syntax
>>> [x**2 for x in (1, 2, 3)] # Add parenthesis
[1, 4, 9]
>>> for x in 1, 2, 3: # Python 3: For normal loops it still works
    print(x**2)
...
1
4
9

两者均创建并调用匿名函数。但是,list(...)表单创建一个生成器函数并将返回的Generator-Iterator传递到list,而使用[...]表单,匿名函数直接使用LIST_APPEND opcodes构建列表。

以下代码获得示例理解及其相应的genExp-passed-to- list的匿名函数的倒数输出:

import dis
def f():
    [x for x in []]
def g():
    list(x for x in [])
dis.dis(f.__code__.co_consts[1])
dis.dis(g.__code__.co_consts[1])

理解的输出为

  4           0 BUILD_LIST               0
              3 LOAD_FAST                0 (.0)
        >>    6 FOR_ITER                12 (to 21)
              9 STORE_FAST               1 (x)
             12 LOAD_FAST                1 (x)
             15 LIST_APPEND              2
             18 JUMP_ABSOLUTE            6
        >>   21 RETURN_VALUE

GenExp的输出为

  7           0 LOAD_FAST                0 (.0)
        >>    3 FOR_ITER                11 (to 17)
              6 STORE_FAST               1 (x)
              9 LOAD_FAST                1 (x)
             12 YIELD_VALUE
             13 POP_TOP
             14 JUMP_ABSOLUTE            3
        >>   17 LOAD_CONST               0 (None)
             20 RETURN_VALUE

您实际上可以证明这两个可以具有不同的结果来证明它们本质上不同:

>>> list(next(iter([])) if x > 3 else x for x in range(10))
[0, 1, 2, 3]
>>> [next(iter([])) if x > 3 else x for x in range(10)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
StopIteration

理解中的表达不会被视为发电机,因为理解不处理StopIteration,而list构造函数则。

它们不一样,list()将评估括号中的内容已经完成后,而不是之前。

Python中的[]有点神奇,它告诉Python将其中的内容包裹为列表,更像是语言的类型提示。

最新更新