0

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.

4 Answers 4

3
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']]]
Sign up to request clarification or add additional context in comments.

1 Comment

best method for sure
0
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']]

Comments

0
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')

2 Comments

Hi, thanks for your response. Im working with a dataset made up off 32870 entries, and these need to be sorted in 173 lists of 190 different lists made up off 2 items. By using your method i close to finishing it but i ended up with an output where there are three lists but hey arent grouped correctly. It now looks like: [[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j'], ['k', 'l']]] The method i used is: final_list = np.array(clean_list).reshape(-1,16435,2) final_list2 = final_list.tolist() How can i fix this? Thanks in a
@Nasrr sorry, but I can't properly understand what's your new task. Can you open a new question with a better description of your input and your desired output? Thanks.
0
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)))

1 Comment

Please add explanations to your code. Code only is not an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.