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)]
Just to put this here for posterity sake, in 2.6 the "start" parameter was added to enumerate like so:
enumerate(sequence, start=1)
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.
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)
).
h = [(i + 1, x) for i, x in enumerate(xrange(2000, 2005))]
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
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)]