Get the nth item of a generator in Python

前端 未结 7 2253
一向
一向 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:33

    Best to use is : example :

    a = gen values ('a','c','d','e')
    

    so the answer will be :

    a = list(a) -> this will convert the generator to a list (it will store in memory)
    

    then when you want to go specific index you will :

    a[INDEX] -> and you will able to get the value its holds 
    

    if you want to know only the count or to do operations that not required store in memory best practice will be : a = sum(1 in i in a) -> this will count the number of objects you have

    hope i made it more simple.

提交回复
热议问题