Python 2.x中重复zip枚举迭代器为何无法推进?代码疑问
Let's break down why your code isn't behaving as expected, with two key issues at play:
1. Python 2's zip() Returns a List (Not an Iterator)
In Python 2, zip(a, b) immediately generates all possible pairs from the input iterators and stores them in a list. This happens before your loop even starts running.
For your code:
b = enumerate('ghi')only has 3 elements, sozip(a, b)creates a list of 3 tuples:[((0, 'a'), (0, 'g')), ((1, 'b'), (1, 'h')), ((2, 'c'), (2, 'i'))].- During this list creation,
ais advanced 3 times (to(2, 'c')) andbis fully exhausted (no elements left).
By the time your loop begins, b is empty. When you call zip(a, b) again inside the loop, it returns an empty list—so your itertools.islice call has nothing to process, and next() does nothing.
2. Incorrect Use of itertools.islice
Even if you switched to itertools.izip (Python 2's equivalent of Python 3's iterator-based zip), your islice syntax is wrong. islice(zip(a, b), 1, 1) creates an iterator that yields no elements (since the start and stop indices are the same). This means next() returns None without advancing any iterators.
To skip one element, you need to either:
- Advance the same iterator your loop is using, or
- Directly consume the next elements from
aandb.
Corrected Code for Python 2.x
Here are two working approaches:
Approach 1: Use itertools.izip and Reuse the Iterator
import itertools a = enumerate('abcdef') b = enumerate('ghi') # Create the izip iterator once to reuse in the loop zip_iter = itertools.izip(a, b) for i, j in zip_iter: print(i, j) if i[0] == 0: # Skip the next element by advancing the same iterator next(zip_iter, None)
Approach 2: Directly Advance the Underlying Iterators
import itertools a = enumerate('abcdef') b = enumerate('ghi') for i, j in itertools.izip(a, b): print(i, j) if i[0] == 0: # Skip the next pair by advancing a and b directly next(a, None) next(b, None)
Both approaches will produce your expected output:
((0, 'a'), (0, 'g')) ((2, 'c'), (2, 'i'))
内容的提问来源于stack exchange,提问作者jing

