将一个列表的内容循环弹出到列表列表中

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

我有一个列表

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

并且我想将列表拆分为多个列表,并且我想要如下所示的输出-

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

这可以使用 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)

复杂度:O(n).


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

如果我对你的问题的理解正确,你想按 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]]

这是一个简单的代码:

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)

输出:

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

编辑

如果

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

然后输出

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

more_itertools是一个第三方库,为此实现了一个工具:

> pip install more_itertools

代码

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]]

可迭代的元素分布在 n 个块中。有关详细信息,请参阅 more_itertools docs


此问题独有的另一种简单方法:

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]]

两个切片列表在从每个子元素过滤 None 时被完全压缩。