How to get the n next values of a generator in a list (python)

后端 未结 5 1442
醉话见心
醉话见心 2020-11-28 11:08

I have made a generator to read a file word by word and it works nicely.

def word_reader(file):
    for line in open(file):
        for p in line.split():
           


        
5条回答
  •  佛祖请我去吃肉
    2020-11-28 11:34

    To get the first n values of a generator, you can use more_itertools.take.

    If you plan to iterate over the words in chunks (eg. 100 at a time), you can use more_itertools.chunked (https://more-itertools.readthedocs.io/en/latest/api.html):

    import more_itertools
    for words in more_itertools.chunked(reader, n=100):
        # process 100 words
    

提交回复
热议问题