2 回答
TA贡献1878条经验 获得超4个赞
您可以使用defaultdict:
from collections import defaultdict
l = [['test', 'testlink', 1],
['test', 'testlink', 2],
['test', 'testlink', 3],
['test', 'testlink', 4],
['test 2', 'test2link', 1],
['test 2', 'test2link', 2],
['test 3', 'test3link', 1],
['test 3', 'test3link', 3],
['test 3', 'test3link', 4]]
d = defaultdict(int)
for first, second, third in l:
if d[(first, second)] < third:
d[(first, second)] = third
要形成您想要使用下一行的格式的结果:
res = [[*key, value] for key, value in d.items()]
如果您不想导入defaultdict,可以使用常规的:
d = {}
for first, second, third in l:
item = d.get((first, second), None)
if not item or item < third:
d[(first, second)] = third
TA贡献1820条经验 获得超9个赞
使用itertools.groupby(doc)的一种解决方案:
rows=[]
rows.append(["test","testlink",1])
rows.append(["test 2","test2link",1])
rows.append(["test 3","test3link",1])
rows.append(["test","testlink",2])
rows.append(["test","testlink",1])
rows.append(["test 2","test2link",1])
rows.append(["test 3","test3link",1])
rows.append(["test ","testlink",3])
rows.append(["test 3","test3link",3])
rows.append(["test ","testlink",4])
rows.append(["test 3","test3link",4])
rows.append(["test 2","test2link",2])
from itertools import groupby
out = []
for v, g in groupby(sorted(rows, key=lambda k: k[0].strip()), lambda k: k[0].strip()):
item = max(g, key=lambda k: k[2])
out.append(item)
from pprint import pprint
pprint(out)
印刷:
[['test ', 'testlink', 4],
['test 2', 'test2link', 2],
['test 3', 'test3link', 4]]
添加回答
举报