You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.x中重复zip枚举迭代器为何无法推进?代码疑问

Why Your Skipping Logic Fails in Python 2.x

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, so zip(a, b) creates a list of 3 tuples: [((0, 'a'), (0, 'g')), ((1, 'b'), (1, 'h')), ((2, 'c'), (2, 'i'))].
  • During this list creation, a is advanced 3 times (to (2, 'c')) and b is 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 a and b.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:07:48