天真的方式,使用sorted() function 和自定义排序键(为dict.items()) 生成的每个(key, value) 对调用)对(键,值)元组列表进行排序:
sorted(a.items(), key=lambda pair: a_list.index(pair[0]))
更快的方法,先创建索引映射:
index_map = {v: i for i, v in enumerate(a_list)}
sorted(a.items(), key=lambda pair: index_map[pair[0]])
这更快,因为index_map 中的字典查找需要 O(1) 恒定时间,而 a_list.index() 调用每次都必须扫描列表,因此需要 O(N) 线性时间。由于对字典中的每个键值对都调用了该扫描,因此朴素排序选项需要 O(N^2) 二次时间,而使用映射可以保持排序效率(O(N log N),线性时间)。
两者都假定a_list 包含在a 中找到的所有 键。但是,如果是这种情况,那么您也可以反转查找并按顺序检索键:
[(key, a[key]) for key in a_list if key in a]
这需要 O(N) 线性时间,并允许在 a_list 中使用 a 中不存在的额外键。
明确地说:O(N) > O(N log N) > O(N^2),见this cheat sheet for reference。
演示:
>>> a = {'ground': 'obj1', 'floor 1': 'obj2', 'basement': 'obj3'}
>>> a_list = ('floor 1', 'ground', 'basement')
>>> sorted(a.items(), key=lambda pair: a_list.index(pair[0]))
[('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]
>>> index_map = {v: i for i, v in enumerate(a_list)}
>>> sorted(a.items(), key=lambda pair: index_map[pair[0]])
[('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]
>>> [(key, a[key]) for key in a_list if key in a]
[('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]