Search code examples
pythonarrayslistsublist

Divide list into sublist following certain pattern


Given an example list a = [311, 7426, 3539, 2077, 13, 558, 288, 176, 6, 196, 91, 54, 5, 202, 116, 95] with n = 16 elements (it will be in general a list of an even number of elements).

I wish to create n/4 lists that would be:

list1 = [311, 13, 6, 5]
list2 = [7426, 558, 196, 202]
list3 = [3539, 288, 91, 116]
list4 = [2077, 176, 54, 95]

(The solution is not taking an element every n such as a[i::3] in a for loop because values are excluded as the sliding window moves to the left)

Thanks for the tips!

UPDATE:

Thanks for the solutions which work well for this particular example. I realized however that my problem is a bit more complex than this.

In the sense that the list a is generated dynamically in the sense the list can decrease or increase. Now my issue is the following, say that the list grows of another group i.e. until 20 elements. Now the output lists should be 5 using the same concept. Example:

a = [311, 7426, 3539, 2077, 1 ,13, 558, 288, 176, 1, 6, 196, 91, 54, 1, 5, 202, 116, 95, 1]

Now the output should be:

list1 = [311, 13, 6, 5]
list2 = [7426, 558, 196, 202]
list3 = [3539, 288, 91, 116]
list4 = [2077, 176, 54, 95]
list5 = [1, 1, 1, 1]

And so on for whatever size of the list.

Thanks again!


Solution

  • I'm assuming the length of the list a is a multiple of 4. You can use numpy for your problem.

    import numpy as np
    a = [...]
    desired_shape = (-1, len(a)//4)
    arr = np.array(a).reshape(desired_shape).transpose().tolist()
    

    Output:

    [[311, 13, 6, 5],
     [7426, 558, 196, 202],
     [3539, 288, 91, 116],
     [2077, 176, 54, 95],
     [1, 1, 1, 1]]
    

    Unpack the list into variables or iterate over them as desirable.

    Consult numpy.transpose, and reshape to understand their usage.