Convert a flat list to list of lists in python

后端 未结 4 1673
眼角桃花
眼角桃花 2020-12-24 07:36

One may want to do the contrary of flattening a list of lists, like here: I was wondering how you can convert a flat list into a list of lists.

In numpy you could do

4条回答
  •  没有蜡笔的小新
    2020-12-24 08:05

    This is usually done using the grouper recipe from the itertools documentation:

    def grouper(n, iterable, fillvalue=None):
        "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return itertools.izip_longest(fillvalue=fillvalue, *args)
    

    Example:

    >>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> list(grouper(2, my_list))
    [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', None)]
    

提交回复
热议问题