Get the nth item of a generator in Python

前端 未结 7 2278
一向
一向 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:15

    one method would be to use itertools.islice

    >>> gen = (x for x in range(10))
    >>> index = 5
    >>> next(itertools.islice(gen, index, None))
    5
    

提交回复
热议问题