Home > Net >  How to merge more lists together within list of lists
How to merge more lists together within list of lists

Time:05-26

could you please advice how to merge n lists together within list of lists? For ex:

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

--> I want to merge each 3 lists together so I get [[7, 8, 0, 6, 0, 0, 0, 0, 0], [4, 0, 0, 0, 7, 5, 6, 0, 1], ... ]

CodePudding user response:

zip will be your friend for this:

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

new_list = [e1 e2 e3 for e1, e2, e3 in zip(list_[::3], list_[1::3], list_[2::3])]

print(new_list)

Output:

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

CodePudding user response:

I guess something like this would work:

original_lists = [[7, 8, 0], [6, 0, 0], [0, 0, 0], [4, 0, 0], [0, 7, 5], [6, 0, 1], [1, 2, 0], [0, 0, 9], [0, 7, 8], [], [], [], [0, 0, 7], [0, 0, 1], [9, 0, 4], [0, 4, 0], [0, 5, 0], [0, 6, 0], [2, 6, 0], [9, 3, 0], [0, 0, 5], [], [], [], [0, 7, 0], [1, 2, 0], [0, 4, 9], [3, 0, 0], [0, 0, 7], [2, 0, 6], [0, 1, 2], [4, 0, 0], [0, 0, 7], [], [], []]
new_list = []
k = 3
assert(len(original_list) % k == 0)
for i in range(0,len(original_list,k):
    x = []
    for l in original_list[i:i k]:
        x.extend(l)
    new_list.append(x)

CodePudding user response:

With an index modulo 3 approach:

lst = # from question

out = [[]]
for i, l in enumerate(lst):
    if not i % 3:
        out[-1].append([])
    out[-1][-1].extend(l)

print(out)

Notice that consecutive empty lists are contracted into a single

EDIT: to keep track of empty lists as well:

out = [[]]
for i, l in enumerate(lst):
    if not i % 3:
        out[-1].append([])
    if not l:
        out[-1][-1].append(l)
    else:
        out[-1][-1].extend(l)
  • Related