Get the nth item of a generator in Python

前端 未结 7 2276
一向
一向 2020-11-28 07:34

Is there a more syntactically concise way of writing the following?

gen = (i for i in xrange(10))
index = 5
for i, v in enumerate(gen):
    if i is index:
           


        
7条回答
  •  被撕碎了的回忆
    2020-11-28 08:16

    I think the best way is :

    next(x for i,x in enumerate(it) if i==n)
    

    (where it is your iterator and n is the index)

    It doesn't require you to add an import (like the solutions using itertools) nor to load all the elements of the iterator in memory at once (like the solutions using list).

    Note 1: this version throws a StopIteration error if your iterator has less than n items. If you want to get None instead, you can use :

    next((x for i,x in enumerate(it) if i==n), None)
    

    Note 2: There are no brackets inside the call to next. This is not a list comprehension, but a generator comprehension, that does not consume the original iterator further than its nth element.

提交回复
热议问题