Ajax
Ajax

Reputation: 179

Creating a nested list inside a nested list in python

I have this nested list:

list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]

Count of sublist elements are always in mulitple of 3. I want to have 3 elments in each sublist. Desired output:

list_1 = [[1,2,3], [1,2,3], [4,5,6],[1,2,3], [4,5,6], [7,8,9]]

I can achieve this but first i have to flatten the list and then create the nested list. My code:

list_1 = [values for sub_list in lists_1 for values in sub_list]  # flatten it first

list_1 = [list_1[i:i+3] for i in range(0, len(list_1), 3)]

Is there a way to skip the flatten step and get the desired result?

Upvotes: 1

Views: 632

Answers (3)

Jan
Jan

Reputation: 43199

To put my two cents in, you could use two generator functions, one that flattens the list (with an arbitrarly nested list) and one that yields pairs of n values:

def recursive_yield(my_list):
    for item in my_list:
        if isinstance(item, list):
            yield from recursive_yield(item)
        else:
            yield item

def taken(gen, number = 3):
    buffer = []
    for item in gen:
        if len(buffer) < number:
            buffer.append(item)
        else:
            yield buffer
            buffer = []
            buffer.append(item)
    if buffer:
        yield buffer
    
result = [x for x in taken(recursive_yield(list_1))]

Here are some examples of the in- / outputs:

list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
# -> [[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

list_1 = [1,2,3,4,5,6]
# -> [[1, 2, 3], [4, 5, 6]]

list_1 = [1,2,[[1,2,4,5], [[[[1,10,9]]]]]]
# -> number = 5
# -> [[1, 2, 1, 2, 4], [5, 1, 10, 9]]

Thus, the solution is much more flexible than slicing alone.

Upvotes: 0

Red
Red

Reputation: 27577

Here is how you can use nested list comprehensions:

list_1 = [[1,2,3],[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9]]

list_1 = [a for b in list_1 for a in b]
list_1 = [list_1[i:i+3] for i in range(0,len(list_1),3)]

print(list_1)

Output:

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

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

You can use a nested list comprehension:

list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
result = [i[j:j+3] for i in list_1 for j in range(0, len(i), 3)]

Output:

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

Upvotes: 4

Related Questions