How to enumerate a range of numbers starting at 1

后端 未结 12 1130
谎友^
谎友^ 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-29 23:51

    Just to put this here for posterity sake, in 2.6 the "start" parameter was added to enumerate like so:

    enumerate(sequence, start=1)

    0 讨论(0)
  • 2020-11-29 23:51

    enumerate is trivial, and so is re-implementing it to accept a start:

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

    Note that this doesn't break code using enumerate without start argument. Alternatively, this oneliner may be more elegant and possibly faster, but breaks other uses of enumerate:

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

    The latter was pure nonsense. @Duncan got the wrapper right.

    0 讨论(0)
  • 2020-11-29 23:53

    Simplest way to do in Python 2.5 exactly what you ask about:

    import itertools as it
    
    ... it.izip(it.count(1), xrange(2000, 2005)) ...
    

    If you want a list, as you appear to, use zip in lieu of it.izip.

    (BTW, as a general rule, the best way to make a list out of a generator or any other iterable X is not [x for x in X], but rather list(X)).

    0 讨论(0)
  • 2020-11-29 23:59

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

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

    I don't know how these posts could possibly be made more complicated then the following:

    # Just pass the start argument to enumerate ...
    for i,word in enumerate(allWords, 1):
        word2idx[word]=i
        idx2word[i]=word
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题