简体   繁体   English

列表是否在 python 'for' 循环的每次迭代中实例化?

[英]Does list instantiates at every iteration of python 'for' loop?

I want to know if the list created (instantiated) and used in for loop will reduce efficiency of my program.我想知道创建(实例化)并在for循环中使用的列表是否会降低我的程序效率。

For example:例如:

for i in range(1, 10000):
     print("This i = ", i)

Please tell me if the list [1,2,3,...,10000] (which is range(1,10000) ) will be generated (or instantiated) at every iteration or not.请告诉我列表[1,2,3,...,10000] (即range(1,10000) )是否会在每次迭代时生成(或实例化)。 Because if Yes, then this is a huge overhead and inefficient program.因为如果是,那么这是一个巨大的开销和低效的程序。

Actually I want to use it like this:其实我想这样使用它:

with open("bbc.txt", 'w', encoding='utf-8') as bbcFile:
    for headline in BS(REQ.get("https://www.bbc.com").text, 'html.parser').find_all('div', {'class':'media__content'}):
        bbcFile.write(" ".join(headline.text.split()) + "\n\n")

In a Python for-statement, as defined by the docs :在 Python for 语句中,如文档所定义

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

According to the aforementioned docs,根据上述文档,

The expression list is evaluated once ;表达式列表被评估一次 it should yield an iterable object.它应该产生一个可迭代的对象。 An iterator is created for the result of the expression_list .expression_list的结果创建一个迭代器。 The suite is then executed once for each item provided by the iterator, in the order returned by the iterator.然后,按照迭代器返回的顺序,对迭代器提供的每个项目执行一次套件。 Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed.使用标准分配规则(请参阅分配语句)依次将每个项目分配给target list ,然后执行suite

So no, whatever expression you are using in to produce an iterable is only evaluated once.所以不,你用来产生可迭代的任何表达式只计算一次。 You could test this out yourself:你可以自己测试一下:

>>> class MyIterable:
...     def __init__(self):
...         print("Initialized")
...     def __iter__(self):
...         yield from (1,2,3)
...
>>> for x in MyIterable():
...     print(x)
...
Initialized
1
2
3
>>>

For Python 3, no.对于 Python 3,没有。 range(1, 10000) creates a range object that produces items when necessary: range(1, 10000)创建一个 range 对象,在必要时生成项目:

>>> range(1, 10000)
range(1, 10000)
>>> type(range(1, 10000))
<class 'range'>

So there is never a list [1, ..., 10000] stored in memory.所以永远不会有一个列表[1, ..., 10000]存储在内存中。

A great SO question to check out is this one , which explains the range object.一个很好的SO问题是this one ,它解释了range对象。

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

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