将每个包含x个项目的列表列表拆分成两倍于每个包含x / 2个项目的列表的列表

时间:2019-09-29 18:54:02

标签: python python-3.x list split

我正在尝试将每个列表包含n个项目的列表分成两个列表,每个列表包含n / 2个项目。

例如

  list_x = [[list_a], [list_b]]

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

我要求:

list_x2 = [[list_a2], [list_b2], [list_c2], [list_d2]]

位置:

list_a2 = ['1','2','3']
list_b2 = ['4','5','6']
list_c2 = ['7','8','9']
list_d2 = ['10','11','12']

我尝试过: All possibilities to split a list into two lists-但希望能深入了解如何将上述解决方案扩展到“带有列表的列表” 方案。

任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:1)

您可以使用列表理解:

list_x = [['1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12']]
n = 2
list_x2 = [l[i: i + len(l) // n] for l in list_x for i in range(0, len(l),  len(l) // n)]

答案 1 :(得分:0)

尝试一下:

list_x = [list_a, list_b]
#[['1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12']]
n = 3
list_x2 = [[l[3*i:3*j+3] for i,j in zip(range(len(l)//n), range(len(l)//n))] for l in list_x]

输出

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

答案 2 :(得分:0)

没有人提供numpy解决方案...可能不是要求的,但这很好;)

list_a = ['1','2','3','4','5','6']
list_b = ['7','8','9','10','11','12']
list_x = [list_a, list_b]

a = np.array(list_x)
w, h = a.shape
a.shape = w*2, h//2

list_x2 = a.tolist()

答案 3 :(得分:0)

from operator import add
from functools import reduce

addlists = lambda l: reduce(add, l)

list_a = ['1','2','3','4','5','6']
list_b = ['7','8','9','10','11','12']
list_x = [list_a, list_b]

k = len(list_a) // len(list_x)

joined = addlists(list_x)
res = list(map(list, zip(*([iter(joined)]*k))))