Turning a list into nested lists in python

后端 未结 8 1913
天涯浪人
天涯浪人 2020-11-30 05:15

Possible Duplicate:
How can I turn a list into an array in python?

How can I turn a list such as:

<         


        
8条回答
  •  旧时难觅i
    2020-11-30 05:41

    The following function expands the original context to include any desired list of lists structure:

    def gen_list_of_lists(original_list, new_structure):
        assert len(original_list) == sum(new_structure), \
        "The number of elements in the original list and desired structure don't match"
            
        list_of_lists = [[original_list[i + sum(new_structure[:j])] for i in range(new_structure[j])] \
                         for j in range(len(new_structure))]
            
        return list_of_lists
    

    Using the above:

    data_list = [0,1,2,3,4,5,6,7,8]
        
    new_list = gen_list_of_lists(original_list=data_list, new_structure=[3,3,3])
    # The original desired outcome of [[0,1,2], [3,4,5], [6,7,8]]
    
    new_list = gen_list_of_lists(original_list=data_list, new_structure=[2,3,3,1])
    # [[0, 1], [2, 3, 4], [5, 6, 7], [8]]
    

提交回复
热议问题