2024-04-26 07:19:10 发布
网友
我有以下格式的列表:
[[<image object1>, source1 , version1],[<image object2>, source2 , version2]...]
我需要比较每个列表并构建一个包含唯一源值的新列表。当有重复的源值时,我需要选择版本值最高的列表。在
另外,这是我应该使用的正确的数据结构吗?在
您可以使用^{}和^{}函数来完成此操作:
>>> 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)
您可以使用^{} 和^{} 函数来完成此操作:
假设您的所有子列表都有相同的三项结构,这似乎是一种非常合理的数据结构,因为您可以始终使用索引[0]、[1]和[2]访问图像对象、源和版本。在
这段代码使源代码成为字典的键,子列表列出这些键的值。在
相关问题 更多 >
编程相关推荐