split a generator/iterable every n items in python (splitEvery)

前端 未结 13 1379
臣服心动
臣服心动 2020-11-27 16:44

I\'m trying to write the Haskel function \'splitEvery\' in Python. Here is it\'s definition:

splitEvery :: Int -> [e] -> [[e]]
    @\'splitEvery\' n@ s         


        
13条回答
  •  醉梦人生
    2020-11-27 17:38

    I think those questions are almost equal

    Changing a little bit to crop the last, I think a good solution for the generator case would be:

    from itertools import *
    def iter_grouper(n, iterable):
        it = iter(iterable)
        item = itertools.islice(it, n)
        while item:
            yield item
            item = itertools.islice(it, n)
    

    for the object that supports slices (lists, strings, tuples), we can do:

    def slice_grouper(n, sequence):
       return [sequence[i:i+n] for i in range(0, len(sequence), n)]
    

    now it's just a matter of dispatching the correct method:

    def grouper(n, iter_or_seq):
        if hasattr(iter_or_seq, "__getslice__"):
            return slice_grouper(n, iter_or_seq)
        elif hasattr(iter_or_seq, "__iter__"):
            return iter_grouper(n, iter_or_seq)
    

    I think you could polish it a little bit more :-)

提交回复
热议问题