2

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!

2 Answers 2

3

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

Comments

0

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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.