How to divide python list into sublists of unequal length?

后端 未结 5 1366
情书的邮戳
情书的邮戳 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:35

    You can also use the .pop() method like this:

    list1 = [1, 2, 1]
    list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
    
    new_list = []
    for chunk in list1:
        new_list.append( [ list2.pop(0) for _ in range(chunk)] )
    print(new_list)
    
    
    # [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
    

    This will modify the original list2.

提交回复
热议问题