How to divide python list into sublists of unequal length?

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

    You could combine the power of itertools.accumulate and list comprehensions:

    In [4]: from itertools import accumulate
    
    In [5]: data = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
    
    In [6]: lengths = [1, 2, 1]
    
    In [7]: [data[end - length:end] for length, end in zip(lengths, accumulate(lengths))]
    Out[7]: [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
    

    itertools.accumulate returns an iterator to a sequence of accumulated sums. This way you could easily calculate the end of each chunk in the source array:

    In [8]: list(accumulate(lengths))
    Out[8]: [1, 3, 4]
    

提交回复
热议问题