Convert a flat list to list of lists in python

后端 未结 4 1649
眼角桃花
眼角桃花 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:17

    >>> l = ['a', 'b', 'c', 'd', 'e', 'f']
    >>> zip(*[iter(l)]*2)
    [('a', 'b'), ('c', 'd'), ('e', 'f')]
    

    As it has been pointed out by @Lattyware, this only works if there are enough items in each argument to the zip function each time it returns a tuple. If one of the parameters has less items than the others, items are cut off eg.

    >>> l = ['a', 'b', 'c', 'd', 'e', 'f','g']
    >>> zip(*[iter(l)]*2)
    [('a', 'b'), ('c', 'd'), ('e', 'f')]
    

    If this is the case then it is best to use the solution by @Sven Marnach

    How does zip(*[iter(s)]*n) work

提交回复
热议问题