简体   繁体   中英

How to merge list of tuple of list into a list of tuples in Python

I have a sample list of data like this:

list_ = [
    (['0.640', '0.630', '0.64'], ['0.61', '0.65', '0.53']), 
    (['20.00', '21.00', '21.00'], ['21.00', '22.00', '22.00']), 
    (['0.025', '0.025', '0.026'], ['0.150', '0.150', '0.130'])
] 

I'm trying to merge all lists in tuple into tuple, which would be the result of list of tuples.

Now I would like to get a merged list as follows

output = [
    ('0.640', '0.630', '0.64', '0.61', '0.65', '0.53'), 
    ('20.00', '21.00', '21.00', '21.00', '22.00', '22.00'), 
    ('0.025', '0.025', '0.026', '0.150', '0.150', '0.130')
]
# or 
output = [
    ['0.640', '0.630', '0.64', '0.61', '0.65', '0.53'], 
    ['20.00', '21.00', '21.00', '21.00', '22.00', '22.00'], 
    ['0.025', '0.025', '0.026', '0.150', '0.150', '0.130']
]

Any help appreciated. Thanks in advance!

from itertools import chain
output = [tuple(chain.from_iterable(t)) for t in list_]

Use chain from itertools .

  • list comprehension
[[item for internal_list_ in tuple_ for item in internal_list_] for tuple_ in list_]
  • numpy
np.array(list_).reshape((len(list_), -1))
output = [x[0]+x[1] for x in list_]

If you want a general solution you don't have to import itertools in this case as others have suggested. This works for n-tuples:

output = [sum([*x], []) for x in list_]

This solution will be superior when you don't have thousands of lists, but inferior otherwise.

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