[英]Multiple usage of generator from list in Python
Basically, I'm in following situation - I generate a list, eg 基本上,我处于以下情况-我生成一个列表,例如
l = [2*x for x in range(10)]
which I iterate through later on multipletimes, eg 我在以后多次反复遍历,例如
for i in l: print i # 0,2,4,6,8,10,12,14,16,18
for i in l: print i # 0,2,4,6,8,10,12,14,16,18
for i in l: print i # 0,2,4,6,8,10,12,14,16,18
The problem is that the list is way too large to fit into memory, hence I use its generator form, ie: 问题在于列表太大而无法容纳到内存中,因此我使用其生成器形式,即:
l = (2*x for x in range(10))
However, after this construction only first iteration works: 但是,在此构造之后,只有第一个迭代有效:
for i in l: print i # 0,2,4,6,8,10,12,14,16,18
for i in l: print i #
for i in l: print i #
Where is the problem? 问题出在哪儿? How may I iterate through it multipletimes?
我如何多次遍历它?
Your generator is exhausted the first time. 您的发电机第一次用尽。 You should recreate your generator each time to renew it:
您应该每次重新创建生成器以进行更新 :
l = (2*x for x in range(10))
for i in l: print i
l = (2*x for x in range(10))
for i in l: print i
(Note: you should use xrange
in python 2 because range
creates a list in memory) (注意:您应该在python 2中使用
xrange
,因为range
在内存中创建了一个列表)
You can create also a shortcut function to help you or even a generator function : 您还可以创建一个快捷功能来帮助您甚至生成器功能 :
def gen():
for i in range(10):
yield 2 * i
and then: 接着:
for i in gen(): print i
for i in gen(): print i
You can also iterate on the generator directly: 您还可以直接在生成器上进行迭代:
for i in (2*x for x in range(10)): print i
for i in (2*x for x in range(10)): print i
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.