Home > Software engineering >  How can I merge elements of a nested sublist from 3 different lists in Python?
How can I merge elements of a nested sublist from 3 different lists in Python?

Time:07-11

I have three lists:

A = [["a", "b", "c"],["f", "b", "a"]]
numbers = [[1, 2 ,3], [1, 2, 3]]
frequency = [[0.2, 0.5, 0.7], [0.1, 0.8, 0.9]]

and want to obtain a combined list as:

comb = [[("a",1,0.2), ("b",2,0.5), ("c",3,0.7)],[("f",1,0.1), ("b",2,0.8), ("a",3,0.9)] 

I tried using join, but sublists are not merging as desired. How could I get the combined list? Thanks!

CodePudding user response:

You can use zip twice:

A = [["a", "b", "c"],["f", "b", "a"]]
numbers = [[1, 2 ,3], [1, 2, 3]]
frequency = [[0.2, 0.5, 0.7], [0.1, 0.8, 0.9]]

output = [list(zip(*zipped)) for zipped in zip(A, numbers, frequency)]
print(output)
# [[('a', 1, 0.2), ('b', 2, 0.5), ('c', 3, 0.7)], [('f', 1, 0.1), ('b', 2, 0.8), ('a', 3, 0.9)]]

Alternatively, you can use itertools.starmap to get an iterator (of iterators):

from itertools import starmap

output = starmap(zip, zip(A, numbers, frequency))

for subzip in output:
    print(*subzip)
# ('a', 1, 0.2) ('b', 2, 0.5) ('c', 3, 0.7)
# ('f', 1, 0.1) ('b', 2, 0.8) ('a', 3, 0.9)

CodePudding user response:

Using list comprehension (although J1-lee's answer is more concise):

result=[[(i,k,j)  for i,k,j in zip(q,w,e)]
        for q,w,e in zip(A,numbers,frequency)]

Using for loop:

result=[]
for q,w,e in zip(A,numbers,frequency):
    temp=[]
    for i,k,j in zip(q,w,e):
        temp.append((i,k,j))
    result.append(temp)
  • Related