Reputation: 1549
I have a list of results, which look like this:
list_results=[([{"A"}], [], [], [1]), ([{"B"}], [], [23], []), ([{"C"}], [55], [], []), ([{"D"}], [422], [], [])] # a list of 4 tuples
And I want to merge each tuple element wise and get the following result:
merged_list=[[{"A"}, {"B"}, {"C"}, {"D"}], [55, 422], [23], [1]] # a list of lists
list1=merged_list[0] #[{"A"}, {"B"}, {"C"}, {"D"}]
list2=merged_list[1] #[55, 422]
list3=merged_list[2] #[23]
list4=merged_list[3] #[1]
(OPTIONAL) Please propose code and time efficient solutions because this transformation will include more than 4 tuples (i.e 100,000 tuples)
Thank you in advance for your help.
Upvotes: 2
Views: 557
Reputation: 179
def merge(ls):
result=[]
ls0=[]
ls1=[]
ls2=[]
ls3=[]
for index in range(len(ls)):
ls0.append(ls[index][0][0])
try:
ls1.append(ls[index][1][0])
except:
pass
try:
ls2.append(ls[index][2][0])
except:
pass
try:
ls3.append(ls[index][3][0])
except:
pass
result.append(ls0)
result.append(ls1)
result.append(ls2)
result.append(ls3)
return result
Hope it works for you.
without using itertools
Upvotes: 0
Reputation: 7812
You can use chain.from_iterable()
:
from itertools import chain
merged_list = list(map(list, map(chain.from_iterable, zip(*list_results))))
Upvotes: 1
Reputation: 117926
You can zip
your list elements together, and use itertools
to chain/flatten the result within a list comprehension.
>>> import itertools
>>> [list(itertools.chain.from_iterable(i)) for i in zip(*list_results)]
[[{'A'}, {'B'}, {'C'}, {'D'}], [55, 422], [23], [1]]
Upvotes: 2