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


当前回答

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

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

其他回答

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

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

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 2.6或更新版本中很简单:

enumerate(range(2000, 2005), 1)

Python 2.5及以上版本不支持start参数,所以你可以创建两个range对象并压缩它们:

r = xrange(2000, 2005)
r2 = xrange(1, len(r) + 1)
h = zip(r2, r)
print h

结果:

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

如果希望创建生成器而不是列表,则可以使用izip。

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

由于这有点啰嗦,我建议编写自己的函数来泛化它:

def enumerate_at(xs, start):
    return ((tup[0]+start, tup[1]) for tup in enumerate(xs))

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

列举(序列,开始= 1)