Python enumerate downwards or with a custom step -
how create python's enumerate function enumerate bigger numbers lesser (descending order, decrement, count down)? or in general, how utilize different step increment/decrement in enumerate?
for example, such function, applied list ['a', 'b', 'c'], start value 10 , step -2, produce iterator [(10, 'a'), (8, 'b'), (6, 'c')].
i haven't found more elegant, idiomatic, , concise way, write simple generator:
def enumerate2(xs, start=0, step=1): x in xs: yield (start, x) start += step examples:
>>> list(enumerate2([1,2,3], 5, -1)) [(5, 1), (4, 2), (3, 3)] >>> list(enumerate2([1,2,3], 5, -2)) [(5, 1), (3, 2), (1, 3)] if don't understand above code, read the python yield keyword explained , difference between python generators vs iterators.
python enumerate
No comments:
Post a Comment