I have a nested list shaped like
mylist = [[a, b, c, d], [e, f, g, h], [i, j, k, l]]
And i need to split the nested lists so that every two items are grouped together like this:
Nested_list = [[[a, b], [c, d], [[e, f], [g, h]], [[i, j], [k, l]]
I tried splitting them by them by usinga for loop that appended them but this doesn't work.
CodePudding user response:
mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
nested_list = [ [i[:2], i[2:]] for i in mylist ]
print(nested_list)
Output:
[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']], [['i', 'j'], ['k', 'l']]]
CodePudding user response:
mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
Nested_list = []
for x in mylist:
Nested_list.append(x[:2])
Nested_list.append(x[2:])
print(Nested_list)
Output: [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j'], ['k', 'l']]
CodePudding user response:
import numpy as np
Nested_list = np.array(mylist).reshape(-1,2,2)
output:
array([[['a', 'b'],
['c', 'd']],
[['e', 'f'],
['g', 'h']],
[['i', 'j'],
['k', 'l']]], dtype='<U1')
CodePudding user response:
from itertools import *
my_list = chain.from_iterable(my_list)
def grouper(inputs, n):
iters = [iter(inputs)] * n
return zip_longest(*iters)
print(list(grouper(my_list, 2)))