How to enumerate a range of numbers starting at 1

后端 未结 12 1131
谎友^
谎友^ 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:08
    >>> list(enumerate(range(1999, 2005)))[1:]
    [(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
    
    0 讨论(0)
  • 2020-11-30 00:11
    >>> h = enumerate(range(2000, 2005))
    >>> [(tup[0]+1, tup[1]) for tup in h]
    [(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
    

    Since this is somewhat verbose, I'd recommend writing your own function to generalize it:

    def enumerate_at(xs, start):
        return ((tup[0]+start, tup[1]) for tup in enumerate(xs))
    
    0 讨论(0)
  • 2020-11-30 00:13
    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
    

    Now h = list(enumerate(xrange(2000, 2005), 1)) works.

    0 讨论(0)
  • 2020-11-30 00:16

    Easy, just define your own function that does what you want:

    def enum(seq, start=0):
        for i, x in enumerate(seq):
            yield i+start, x
    
    0 讨论(0)
  • 2020-11-30 00:18

    As you already mentioned, this is straightforward to do in Python 2.6 or newer:

    enumerate(range(2000, 2005), 1)
    

    Python 2.5 and older do not support the start parameter so instead you could create two range objects and zip them:

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

    Result:

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

    If you want to create a generator instead of a list then you can use izip instead.

    0 讨论(0)
  • 2020-11-30 00:18

    Python 3

    Official documentation: enumerate(iterable, start=0)

    So you would use it like this:

    >>> 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')]
    
    0 讨论(0)
提交回复
热议问题