Turning a list into nested lists in python

后端 未结 8 1895
天涯浪人
天涯浪人 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条回答
  • 2020-11-30 05:26

    This assumes that data_list has a length that is a multiple of three

    i=0
    new_list=[]
    while i<len(data_list):
      new_list.append(data_list[i:i+3])
      i+=3
    
    0 讨论(0)
  • 2020-11-30 05:26

    I hope this will be helpful to you. It converts a list into a list of lists

    list1= [ i for i in range(0,8+1] nested =[] for i in list1: if len(nested) !=0: if i %3!=0: nested.append([i]) else: nested[len(nested)-1].append(i) else: nested.append([i]) print(nested

    0 讨论(0)
  • 2020-11-30 05:34

    Do you have any sort of selection criteria from your original list?

    Python does allow you to do this:

    new_list = []
    new_list.append(data_list[:3])
    new_list.append(data_list[3:6])
    new_list.append(data_list[6:])
    
    print new_list
    # Output:  [ [0,1,2] , [3,4,5] , [6,7,8] ]
    
    0 讨论(0)
  • 2020-11-30 05:37

    This groups each 3 elements in the order they appear:

    new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]
    

    Give us a better example if it is not what you want.

    0 讨论(0)
  • 2020-11-30 05:40

    Something like:

    map (lambda x: data_list[3*x:(x+1)*3], range (3))
    
    0 讨论(0)
  • 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]]
    
    0 讨论(0)
提交回复
热议问题