Splitting a list into N parts of approximately equal length

前端 未结 30 1759
迷失自我
迷失自我 2020-11-22 16:16

What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in o

30条回答
  •  再見小時候
    2020-11-22 16:46

    Let's say you want to split a list [1, 2, 3, 4, 5, 6, 7, 8] into 3 element lists

    like [[1,2,3], [4, 5, 6], [7, 8]], where if the last remaining elements left are less than 3, they are grouped together.

    my_list = [1, 2, 3, 4, 5, 6, 7, 8]
    my_list2 = [my_list[i:i+3] for i in range(0, len(my_list), 3)]
    print(my_list2)
    

    Output: [[1,2,3], [4, 5, 6], [7, 8]]

    Where length of one part is 3. Replace 3 with your own chunk size.

提交回复
热议问题