我使用的是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中如何获得想要的结果?


当前回答

from itertools import count, izip

def enumerate(L, n=0):
    return izip( count(n), L)

# if 2.5 has no count
def count(n=0):
    while True:
        yield n
        n+=1

现在h = list(enumerate(xrange(2000, 2005), 1))工作了。

其他回答

H = [(i + 1, x) for i, x in enumerate(xrange(2000, 2005))]

只是为了子孙后代起见,在2.6中添加了"start"参数来枚举:

列举(序列,开始= 1)

好吧,我觉得自己有点傻……有什么理由不去做 [(a+1,b) for (a,b) in enumerate(r)] ?如果你不能正常工作,也没有问题:

>>> r = range(2000, 2005)
>>> [(a+1,b) for (a,b) in enumerate(r)]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

>>> enumerate1 = lambda r:((a+1,b) for (a,b) in enumerate(r)) 

>>> list(enumerate1(range(2000,2005)))   # note - generator just like original enumerate()
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

我不知道这些帖子怎么可能比下面的更复杂:

# Just pass the start argument to enumerate ...
for i,word in enumerate(allWords, 1):
    word2idx[word]=i
    idx2word[i]=word

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

import itertools as it

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

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

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