-2

I am trying to split a list of lists, each with n items, into a list of twice as many lists, each containing n/2 items.

E.g.

  list_x = [[list_a], [list_b]]

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

I require:

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

Where:

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

I have tried: All possibilities to split a list into two lists - but would appreciate insight on how to extend some of the mentioned solutions to the 'lists with a list' scenario.

Any assistance appreciated.

PavK0791
  • 71
  • 2
  • 7

4 Answers4

1

You can use list comprehension:

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)]
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
0

Try this :

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]

Output:

[[['1', '2', '3'], ['4', '5', '6']], [['7', '8', '9'], ['10', '11', '12']]]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

No one offered a numpy solution... It may not be what's asked for, but it's nice ;)

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()
zvone
  • 18,045
  • 3
  • 49
  • 77
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))))
kuco 23
  • 786
  • 5
  • 18