Python的比较列表的列表
问题描述:
我有一个列表的列表格式如下:Python的比较列表的列表
[[<image object1>, source1 , version1],[<image object2>, source2 , version2]...]
我需要比较每个列表和构建包含独特的来源值列表的新列表。当有重复的源值时,我需要选择具有最高版本值的列表。
另外,这是我应该使用的正确的数据结构吗?
答
您可以使用itertools.groupby
和max
功能为:
>>> lst = [['foo', 1, 2], ['asdf', 2, 5], ['bar', 1, 3]]
>>> import itertools as it
>>> from operator import itemgetter
>>> [max(items, key=itemgetter(2))
for _,items in it.groupby(sorted(lst, key=itemgetter(1)), key=itemgetter(1))]
[['bar', 1, 3], ['asdf', 2, 5]]
答
假设所有的子表有相同的三个项目的结构,这似乎是一个相当合理的数据结构来使用,因为你可以随时使用索引[0],[1]和[2]访问图像对象,源和版本。
此代码将源代码作为字典的键,并将这些键的值列入子列表。
bigList = [['foo', 1, 2], ['asdf', 2, 5], ['bar', 1, 3]]
uniqueSources = {}
for sublist in bigList:
currentSource = sublist[1]
if currentSource in uniqueSources:
if sublist[2] > uniqueSources[currentSource][2]:
uniqueSources[currentSource] = sublist
else: uniqueSources[currentSource] = sublist
dupesRemoved = list(uniqueSources.values())
print(dupesRemoved)