![](/img/trans.png)
[英]Merge the first elements in a list a tuples if the second elements are the same?
[英]merge elements from list of tuples if the first array is the same
我有一個元組列表:
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'))]
我想將每個元素與相同的第一個數組合並以獲得這個 output:
[('SQ010', ('sh001', '1-10'), ('sh002', '5-15'), ('sh003', '6-16'), ('sh004', '7-17')), ('SQ020', ('sh001', '8-18'), ('sh002', '9-19'),('sh003', '10-20'))]
我嘗試使用 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
結果:
[(('sh001', '1-10'), ('sh002', '5-15'), ('sh003', '6-16'), ('sh004', '7-17')), (('sh001', '8-18'), ('sh002', '9-19'), ('sh003', '10-20'))]
我不明白為什么我會丟失 SQXXX 部分以及如何獲得所需的 output。 謝謝你
SQXXX
部分是您已擺脫的_
變量。 嘗試:
output_list = [(i,) + tuple(i[1] for i in e) for i, e in groupby(seqList, lambda x: x[0])]
給予:
[('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.