简体   繁体   中英

Merge a list of tuples element wise and transform it to a list of lists

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 (ie 100,000 tuples)

Thank you in advance for your help.

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]]

You can use chain.from_iterable() :

from itertools import chain

merged_list = list(map(list, map(chain.from_iterable, zip(*list_results))))
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

  • establish 4 lists
  • the try except is just to avoid appending the empty items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM