How to enumerate a range of numbers starting at 1

后端 未结 12 1133
谎友^
谎友^ 2020-11-29 23:42

I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0):

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

12条回答
  •  粉色の甜心
    2020-11-30 00:06

    Ok, I feel a bit stupid here... what's the reason not to just do it with something like
    [(a+1,b) for (a,b) in enumerate(r)] ? If you won't function, no problem either:

    >>> 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)]
    

提交回复
热议问题