pythonlistsublist

Splitting a python list into 4 sub-lists that are as even as possible


I'm trying to split a python list into four groups that are as even as possible, so for example, if the original list was [1, 2, 3, 4, 5, 6, 7, 8], then the resulting four sub-lists would be [1, 5] [2,6] [3,7] [4,8] where the code goes through each number in the original list and assigns them to a different group, and once it reaches group 4, it goes back to assigning to group 1.

If the original list is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] then the resulting four groups should be [1,5,9] [2,6,10] [3,7] [4,8] where two groups have 3 items, and the other two groups have 2 items--making the groups as even as possible.

Any idea how I could achieve this?


Solution

  • Try this, it splits the input list into sublists in the round-robin fashion you desire:

    def round_robin_sublists(l, n=4):
        lists = [[] for _ in range(n)]
        i = 0
        for elem in l:
            lists[i].append(elem)
            i = (i + 1) % n
        return lists
    
    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    sublist = round_robin_sublists(l) # [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]