Jack
Jack

Reputation: 33

Cyclically pop the contents of one list into a list of lists

I have a list

main_list = [1,2,3,4,5,6,7,8,9,10,11,12]

and I want to split the lists into multiple lists and I want the output as shown below-

list1 = [1,9]    
list2 = [2,10]    
list3 = [3,11]    
list4 = [4,12]    
list5 = [5]    
list6 = [6]    
list7 = [7]
list8 = [8]

Upvotes: 1

Views: 171

Answers (4)

pylang
pylang

Reputation: 44525

more_itertools is a third-party library that implements a tool for this:

> pip install more_itertools

Code

import more_itertools as mit


iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

[list(c) for c in mit.distribute(8, iterable)]
# [[1, 9], [2, 10], [3, 11], [4, 12], [5], [6], [7], [8]]

Elements of an iterable are distributed among the n chunks. See more_itertools docs for details.


Another simple approach, unique to this problem:

import itertools as it


lst, n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 8

[list(filter(None, i)) for i in it.zip_longest(lst[:n], lst[n:])]
# [[1, 9], [2, 10], [3, 11], [4, 12], [5], [6], [7], [8]]

Two sliced lists are fully zipped while filtering None from each sub-element.

Upvotes: 0

Alperen
Alperen

Reputation: 4612

Here is a simple code:

main_list = [1,2,3,4,5,6,7,8,9,10,11,12]

list_count = 8
lists = [[] for _ in range(list_count)]

for count, item in enumerate(main_list):
    lists[count % list_count].append(item)

print(lists)

Output:

[[1, 9], [2, 10], [3, 11], [4, 12], [5], [6], [7], [8]]

EDIT

If

main_list = [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2)]

then output

[[(1, 1), (3, 1)], [(1, 2), (3, 2)], [(1, 3)], [(1, 4)], [(2, 1)], [(2, 2)], [(2, 3)], [(2, 4)]]

Upvotes: 0

cs95
cs95

Reputation: 402553

This can be solved in a matter of lines using itertools.cycle.

from itertools import cycle

main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
lists = [[] for _ in range(8)]

for x, y in zip(cycle(lists), main_list):
     x.append(y)

Complexity: O(n).


print(lists)
[[1, 9], [2, 10], [3, 11], [4, 12], [5], [6], [7], [8]]

Upvotes: 4

Eric Duminil
Eric Duminil

Reputation: 54233

If I understand your problem correctly, you want to group the integers by modulo 8:

from itertools import groupby

def f(x):
    return (x-1) % 8

main_list = [1,2,3,4,5,6,7,8,9,10,11,12]

main_list.sort(key=f)
print(main_list)
# [1, 9, 2, 10, 3, 11, 4, 12, 5, 6, 7, 8]

print([list(l) for _,l in groupby(main_list, key=f)])
# [[1, 9], [2, 10], [3, 11], [4, 12], [5], [6], [7], [8]]

Upvotes: 1

Related Questions