根据另一个列表对列表进行排序

2024-04-20 07:14:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何根据sorter_list中的项目顺序对lista排序:

lista = [["John", "B3"],["Robert", "P3"], ["Thomas", "S2"]]

sorter_list = ["P3", "S2", "B3"]

结果将是:

^{pr2}$

问候


Tags: 项目排序顺序thomasjohnrobertlistb3
3条回答

尽管@F.J有一个完美的解决方案,但我的问题是,为什么不首先使用字典来存储这种数据?在

带字典:

d = {'B3': 'John', 'P3': 'Robert', 'S2': 'Thomas'}
sorter = ["P3", "S2", "B3"]
print([(d[key], key) for key in sorter])

输出:

^{pr2}$

另外:您还应该检查collections模块的OrderedDict。在

更新:

当然,您可以将这些值存储为列表,这样就可以保存多个值:

带字典:

d = {'B3': [('John', 123)], 'P3': [('Robert', 465), ('Andres', 468)], 'S2': [('Thomas', 19)]}
sorter = ('P3', 'B3', 'S2')
print([(d[key], key) for key in sorter])

输出:

[([('Robert', 465), ('Andres', 468)], 'P3'), ([('John', 123)], 'B3'), ([('Thomas', 19)], 'S2')]

在这种情况下,您还可以在字典中使用字典:

d = {'B3': {'John': 123}, 'P3': {'Robert': 465, 'Andres': 468}, 'S2': {'Thomas': 19}}

以后查找会容易得多。

您可以在O(N)中通过构建一个字典来实现这一点,其中的键是B3S2

lookup_dict = dict( (item[1],item) for item in lista)
sorted_lista = [ lookup_dict[key] for key in sorter_list ]

{cd3>已经利用了你的事实。在

假设sorter_list中始终有一个条目与lista中每个列表的第二个元素相匹配:

sorted_lista = sorted(lista, key=lambda lst: sorter_list.index(lst[1]))

相关问题 更多 >