简体   繁体   English

如何将列表元组列表合并为 Python 中的元组列表

[英]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 .使用来自itertools chain

  • 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.如果你想要一个通用的解决方案,你不必像其他人建议的那样在这种情况下导入itertools This works for n-tuples:这适用于 n 元组:

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

This solution will be superior when you don't have thousands of lists, but inferior otherwise.当您没有数以千计的列表时,此解决方案会更胜一筹,否则就逊色了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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