简体   繁体   English

Python:列表理解的for循环性能

[英]Python: performance of for loops over a list comprehension

In the instance where I iterate a list comprehension via a for-loop: 在通过for循环迭代列表理解的实例中:
Is the list comprehension cached when the for loop is executed, or is the list re-generated on every execution? 是在执行for循环时缓存列表推导,还是在每次执行时重新生成列表?

In other words, would these two examples perform differently? 换句话说,这两个例子的表现会有所不同吗?

for x in [list comprehension]  

vs

list_comprehension = [list comprehension]
for x in list_comprehension

I could use an iterator, which I believe uses a generator, but I'm just curious about the Python for-loop execution here. 我可以使用迭代器,我相信可以使用生成器,但是我对这里的Python for循环执行感到好奇。

When you do 当你做

for x in [list comprehension]:

the entire list is built before the for loop starts. 整个列表是在for循环开始之前构建的。 Its basically equivalent to the second example except for the variable assignment. 除了变量分配外,它基本上等同于第二个示例。

a list comprehension returns a list. 列表理解返回一个列表。 The only difference between your two examples is that you're binding the output list to a variable in the second. 两个示例之间的唯一区别是,第二个示例将输出列表绑定到变量。

A generator expression returns an iterator, which means that: 生成器表达式返回迭代器,这意味着:

  • It won't get evaluated until you use it 除非您使用它,否则它不会得到评估
  • If you want to use it more than once you'll have to generate it each time. 如果要多次使用它,则必须每次都生成它。

with this command : list_comprehension = [list comprehension] actually you create another pointer to that part of memory that array have been saved ! 使用以下命令: list_comprehension = [list comprehension]实际上,您创建了另一个指向数组已保存的内存部分的指针!

So the for loop is same in tow case ! 所以for循环在拖曳情况下是相同的! see this Demo: 看到这个演示:

>>> a=[1,2,4]
>>> b=a
>>> b
[1, 2, 4]
>>> a
[1, 2, 4]
>>> a.append(7)
>>> a
[1, 2, 4, 7]
>>> b
[1, 2, 4, 7]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM