我的子列表中充满了自己的子列表。如果子子列表在索引1处共享公共值,那么我想通过合并/组合子子列表中的项来将两个子列表合并为一个子列表以创建一个子子列表。
l = [[
['Sublist1','AAA','10','Apple,Pear,Banana'],
['Sublist1','AAA','50','Peach,Orange,Banana'],
['Sublist1','DDD','3','Bike,Street']
],[
['Sublist2','CCC','50','Tomator,Lemmon'],
['Sublist2','EEE','30','Phone,Sign'],
['Sublist2','CCC','90','Strawberry'],
['Sublist2','FFF','30','Phone,Sign']
],[
['Sublist3','BBB','100','Tomator,Lemmon'],
['Sublist3','BBB','100','Pear'],
['Sublist3','FFF','90','Strawberry'],
['Sublist3','FFF','50','']
]]
例如,如果子子列表在索引1处共享AAA,则合并索引2和3处的项目。在这种情况下,10和50将变为'10,50',以及'Apple,Pear,Banana'和'Peach,Orange,Banana'将成为'Apple,Pear,Banana,Peach,Orange,Banana'。
Desired_Result = [[
['Sublist1','AAA','10,50','Apple,Pear,Banana,Peach,Orange'],
['Sublist1','DDD','3','Bike,Street']
],[
['Sublist2','CCC','50,90','Tomator,Lemmon,Strawberry'],
['Sublist2','EEE','30','Phone,Sign'],
['Sublist2','FFF','30','Phone,Sign']
],[
['Sublist3','BBB','100,100','Tomator,Lemmon,Pear'],
['Sublist3','FFF','90,50','Strawberry']
]]
答案 0 :(得分:0)
你能试试吗?
我认为样本'Sublist2'
中'FFF'
前面有l
。
def merge(lst):
def j(sq):
return ",".join(sq)
def m(sl):
dic = {}
for ssl in sl:
k = tuple(ssl[0:2])
try:
v = dic[k]
except KeyError:
dic[k] = v = (set(), set())
v[0].update( set(ssl[2].split(',')) )
v[0].discard('')
v[1].update( set(ssl[3].split(',')) )
v[1].discard('')
return [ list(k) + [j(v[0])] + [j(v[1])] for k, v in sorted(dic.iteritems()) ]
return [ m(sl) for sl in lst ]
for sl in merge(l):
print sl