问题描述
我有 zip
对象:
L_RANGES = zip(range(10, 20), range(11, 21))
首次调用 L_RANGES
没问题:
print(type(L_RANGES))
for a, b in L_RANGES:
print(a, b)
输出:
<class 'zip'>
10 11
11 12
12 13
13 14
14 15
15 16
16 17
17 18
18 19
19 20
接下来的电话不显示任何内容。有没有办法维护或重置它。到目前为止我可以将其转换为列表:
Bu the next calls do not display anything. Is there any way to maintain or reset that. So far I can just convert it to the list:
L_RANGES = list(zip(range(10, 20), range(11, 21)))
推荐答案
如果你要创造每次循环时都会生成一个生成器,它可以解决所有问题,因为您可以多次重复使用它。为此,将 L_RANGES
从简单生成器转换为 lambda
创建生成器,但不要忘记调用每次使用()
:
If you were to create a generator each time you loop, that would solve everything, because you could reuse that multiple times. For that, convert L_RANGES
from a simple generator to a lambda
creating generators, but don't forget to "call" it each time with ()
:
L_RANGES = lambda: zip(range(10, 20), range(11, 21))
for a, b in L_RANGES():
print(a, b)
for a, b in L_RANGES():
print(a, b)
#works as many times as you want
与其他答案相比,这不占用内存(这是转换为列表的缺点),并且每次要循环时不需要多个变量(通过使用 tee
)这使得这种方式更加灵活(如果需要,您可以迭代1000次,而无需创建 L_RANGES_1 ... L_RANGES_999
)例如:
Compared to the other answers this doesn't take up memory (which is the downside of converting to a list) and doesn't require multiple variables for each time you want to loop (by using tee
) which makes this way more flexible (you can iterate 1000 times if necessary, without creating L_RANGES_1...L_RANGES_999
) for example:
for i in range(1000):
for a, b in L_RANGES():
print(a, b)
这篇关于在python 3中重用zip迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!