简体   繁体   English

如果第一个数组相同,则合并元组列表中的元素

[英]merge elements from list of tuples if the first array is the same

I have a list of tuples:我有一个元组列表:

seqList=[('SQ010', ('sh001', '1-10')), ('SQ010', ('sh002', '5-15')), ('SQ010', ('sh003', '6-16')), ('SQ010', ('sh004', '7-17')), ('SQ020', ('sh001', '8-18')), ('SQ020', ('sh002', '9-19')), ('SQ020', ('sh003', '10-20'))]

I want to merge every element with the same first array to have this output:我想将每个元素与相同的第一个数组合并以获得这个 output:

[('SQ010', ('sh001', '1-10'), ('sh002', '5-15'), ('sh003', '6-16'), ('sh004', '7-17')), ('SQ020', ('sh001', '8-18'), ('sh002', '9-19'),('sh003', '10-20'))]

I have tried with groupby with the following code:我尝试使用 groupby 使用以下代码:

from itertools import groupby
output_list = [tuple(i[1] for i in e) for _, e in groupby(seqList, lambda x: x[0])]
print output_list

it result:结果:

[(('sh001', '1-10'), ('sh002', '5-15'), ('sh003', '6-16'), ('sh004', '7-17')), (('sh001', '8-18'), ('sh002', '9-19'), ('sh003', '10-20'))]

I don't understand why I loose the SQXXX part and how to have the desired output.我不明白为什么我会丢失 SQXXX 部分以及如何获得所需的 output。 thank you谢谢你

The SQXXX part is the _ variable that you have gotten rid of. SQXXX部分是您已摆脱的_变量。 Try:尝试:

output_list = [(i,) + tuple(i[1] for i in e) for i, e in groupby(seqList, lambda x: x[0])]

Giving:给予:

[('SQ010', ('sh001', '1-10'), ('sh002', '5-15'), ('sh003', '6-16'), ('sh004', '7-17')), ('SQ020', ('sh001', '8-18'), ('sh002', '9-19'), ('sh003', '10-20'))]

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

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