Convert a flat list to list of lists in python

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

    Another way to create a list of lists can be simplified as shown below:

    >>>MyList = ['a','b','c','d','e','f']
    # Calculate desired row/col
    >>>row = 3
    >>>col = 2
    >>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
    >>>NewList
    [['a', 'b', 'c'], ['d', 'e', 'f']]
    

    This can method can be extended to produce any row and column size. If you select row and column values such that row*col >len(MyList), the sublist (row) containing the last value in MyList will end there, and NewList will simply be filled with the appropriate number of empty lists to satisfy the row/col specifications

    >>>MyList = ['a','b','c','d','e','f','g','h']
    >>>row = 3
    >>>col = 3
    >>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
    >>>NewList
    [['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]
    
    >>>row = 4
    >>>col = 4
    >>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
    [['a', 'b', 'c', 'd'], ['e', 'f', 'g','h'], [], []]
    

提交回复
热议问题