我使用的是Python 2.5,我想要一个这样的枚举(从1开始而不是0):

[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

我知道在Python 2.6中你可以这样做:h = enumerate(range(2000, 2005), 1)来给出上面的结果,但在python2.5中你不能…

使用Python 2.5:

>>> h = enumerate(range(2000, 2005))
>>> [x for x in h]
[(0, 2000), (1, 2001), (2, 2002), (3, 2003), (4, 2004)]

有没有人知道在Python 2.5中如何获得想要的结果?


当前回答

Python 3

Python官方文档:enumerate(可迭代,start=0)

您不需要像这里的其他答案所建议的那样编写自己的生成器。内置的Python标准库已经包含了一个函数,它可以做你想要的事情:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

内置函数等价于:

def enumerate(sequence, start=0):
  n = start
  for elem in sequence:
    yield n, elem
    n += 1

其他回答

在Python 2.5中最简单的方法是:

import itertools as it

... it.izip(it.count(1), xrange(2000, 2005)) ...

如果您需要一个列表,就像您看起来的那样,使用zip来代替它。

(顺便说一句,作为一般规则,从生成器或任何其他可迭代对象X中创建列表的最佳方法不是[X for X in X],而是list(X))。

>>> list(enumerate(range(1999, 2005)))[1:]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

Enumerate很简单,重新实现它来接受start也很简单:

def enumerate(iterable, start = 0):
    n = start
    for i in iterable:
        yield n, i
        n += 1

注意,使用不带start参数的enumerate不会破坏代码。或者,这个联机程序可能更优雅,也可能更快,但破坏了enumerate的其他用法:

enumerate = ((index+1, item) for index, item)

后者纯粹是一派胡言。@邓肯的包装是正确的。

Python 3

Python官方文档:enumerate(可迭代,start=0)

您不需要像这里的其他答案所建议的那样编写自己的生成器。内置的Python标准库已经包含了一个函数,它可以做你想要的事情:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

内置函数等价于:

def enumerate(sequence, start=0):
  n = start
  for elem in sequence:
    yield n, elem
    n += 1

很简单,只要定义你自己想要的函数:

def enum(seq, start=0):
    for i, x in enumerate(seq):
        yield i+start, x