How to divide python list into sublists of unequal length?

后端 未结 5 1522
情书的邮戳
情书的邮戳 2021-01-25 22:30

I am trying to divide a list of elements which are comma separated into chunks of unequal length. How can I divide it?

list1 = [1, 2, 1]
list2 = [\"1.1.1.1\", \"         


        
5条回答
  •  野性不改
    2021-01-25 23:36

    Yet another solution

    list1 = [1,2,1]
    list2 = ["1.1.1.1","1.1.1.2","1.1.1.3","1.1.1.4"]
    
    chunks = []
    count = 0
    for size in list1:
        chunks.append([list2[i+count] for i in range(size)])
        count += size
    print(chunks)
    
    # [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
    

提交回复
热议问题