在我的列表中查找最高版本

我有一个列表列表:


['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]

我想过滤列表以返回每个唯一第一个元素的第三个元素的最大值。


我想要的结果是:


['test ', 'testlink', 4]

['test 2', 'test2link', 2]

['test 3', 'test3link', 4]

我正在努力寻找一种方法来做到这一点。下面的代码块进入我的排序列表,但在那之后我被卡住了。


#create some dummy data

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])

#filter out duplicates

newRows = []

for elem in rows:

    if elem not in newRows:

        newRows.append(elem)

rows = newRows

#sort the lists

rows = sorted(rows,key=lambda x: (x[0],x[2]))

谢谢所有排序给出的答案都可以在我的 Ironpython 环境中工作


沧海一幻觉
浏览 102回答 2
2回答

UYOU

您可以使用defaultdict:from collections import defaultdictl = [['test', 'testlink', 1],&nbsp; &nbsp; &nbsp;['test', 'testlink', 2],&nbsp; &nbsp; &nbsp;['test', 'testlink', 3],&nbsp; &nbsp; &nbsp;['test', 'testlink', 4],&nbsp; &nbsp; &nbsp;['test 2', 'test2link', 1],&nbsp; &nbsp; &nbsp;['test 2', 'test2link', 2],&nbsp; &nbsp; &nbsp;['test 3', 'test3link', 1],&nbsp; &nbsp; &nbsp;['test 3', 'test3link', 3],&nbsp; &nbsp; &nbsp;['test 3', 'test3link', 4]]d = defaultdict(int)for first, second, third in l:&nbsp; &nbsp; if d[(first, second)] < third:&nbsp; &nbsp; &nbsp; &nbsp;d[(first, second)] = third要形成您想要使用下一行的格式的结果:res = [[*key, value] for key, value in d.items()]如果您不想导入defaultdict,可以使用常规的:d = {}for first, second, third in l:&nbsp; &nbsp; item = d.get((first, second), None)&nbsp; &nbsp; if not item or item < third:&nbsp; &nbsp; &nbsp; &nbsp;d[(first, second)] = third

慕妹3146593

使用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 groupbyout = []for v, g in groupby(sorted(rows, key=lambda k: k[0].strip()), lambda k: k[0].strip()):&nbsp; &nbsp; item = max(g, key=lambda k: k[2])&nbsp; &nbsp; out.append(item)from pprint import pprintpprint(out)印刷:[['test ', 'testlink', 4],&nbsp;['test 2', 'test2link', 2],&nbsp;['test 3', 'test3link', 4]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python