简体   繁体   中英

Simplest way to get the first n elements of an iterator

How can I get the first n elements of an iterator (generator) in the simplest way? Is there something simpler than, eg

def firstN(iterator, n):
  for i in range(n):
    yield iterator.next()

print list(firstN(it, 3))

I can't think of a nicer way, but maybe there is? Maybe a functional form?

Use itertools.islice() :

from itertools import islice
print list(islice(it, 3))

This'll yield the next 3 elements from it , then stop.

不使用itertools

(t[0] for t in zip(L, range(3)))

I've come up myself now with this:

[ iterator.next() for i in range(3) ]

(or just with (…) instead of […] if you just need another iterator.)

And I think it suits me just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM