[英]Python - Use two zipped lists multiple times
I have the following zip: a = zip(list_a, list_b)
.我有以下 zip:
a = zip(list_a, list_b)
。 It was always my understanding that once I zipped a
, it would stay zipped.这一直是我的理解是,一旦我拉上
a
,它会留压缩。 Such that the following would work:这样就可以了:
for iteration in range(100):
for i, j in a:
# do something
But I noticed that on the second iteration a
was empty.但是我注意到在第二次迭代中
a
是空的。 First of all, is my understanding of zip
correct, and secondly, is there a simple single line alternative that would fit in this situation?首先,我对
zip
理解是否正确,其次,是否有适合这种情况的简单单行替代方案?
zip
returns an iterator; zip
返回一个迭代器; it produces each pair once, then it's done.它产生每对一次,然后就完成了。 So the solution is usually to just inline the
zip
in the loop so it's recreated each time:因此,解决方案通常是将
zip
内联到循环中,以便每次都重新创建它:
for iteration in range(100):
for i, j in zip(list_a, list_b):
# do something
or if that doesn't work for some reason, just list
-ify the zip
iterator up front so it's reusable:或者如果由于某种原因这不起作用,只需在前面
list
-ify zip
迭代器,以便它可以重用:
a = list(zip(list_a, list_b))
and then use your original looping code.然后使用您的原始循环代码。
So, in the event that you actually just want to repeat your iterator n
times, but not store anything intermediate:因此,如果您实际上只想重复迭代器
n
次,但不存储任何中间内容:
import itertools
def repeat_iter(iterator, n):
for it in itertools.tee(iterator, n):
yield from it
This would be more useful if you need to pass your iterator around.如果您需要传递迭代器,这将更有用。 The nested
for
loop in the accepted answer is probably sufficient for most use-cases.对于大多数用例来说,接受的答案中的嵌套
for
循环可能就足够了。
Usage:用法:
In [3]: a, b = [1, 2, 3], [4, 5, 6]
In [4]: g = repeat_iter(zip(a, b), 2)
In [5]: next(g)
Out[5]: (1, 4)
In [6]: next(g)
Out[6]: (2, 5)
In [7]: next(g)
Out[7]: (3, 6)
In [8]: next(g)
Out[8]: (1, 4)
In [9]: next(g)
Out[9]: (2, 5)
In [10]: next(g)
Out[10]: (3, 6)
In [14]: next(g)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-14-e734f8aca5ac> in <module>
----> 1 next(g)
If instead, you want to repeatedly iterate over zip(a, b)
forever, you could also use itertools.cycle
:相反,如果你想永远重复迭代
zip(a, b)
,你也可以使用itertools.cycle
:
>>> c = itertools.cycle(zip(a, b))
>>> next(c)
(1, 4)
.
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.