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

前端 未结 13 1420
臣服心动
臣服心动 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:25

    this will do the trick

    from itertools import izip_longest
    izip_longest(it[::2], it[1::2])
    

    where *it* is some iterable


    Example:

    izip_longest('abcdef'[::2], 'abcdef'[1::2]) -> ('a', 'b'), ('c', 'd'), ('e', 'f')
    

    Let's break this down

    'abcdef'[::2] -> 'ace'
    'abcdef'[1::2] -> 'bdf'
    

    As you can see the last number in the slice is specifying the interval that will be used to pick up items. You can read more about using extended slices here.

    The zip function takes the first item from the first iterable and combines it with the first item with the second iterable. The zip function then does the same thing for the second and third items until one of the iterables runs out of values.

    The result is an iterator. If you want a list use the list() function on the result.

提交回复
热议问题