我有这段代码
relations = dict()
relations[('a','b','c')] = 'first'
relations[('a','c','c')] = 'third'
relations[('d','b','c')] = 'second'
relations_sorted = sorted(relations.keys(), key=lambda tup: tup[1])
for key in relations_sorted:
print( key, relations[key])
这将打印按键元组的第二个元素排序的字典(在StackOverflow上找到的解决方案)。
(('d', 'b', 'c'), 'second')
(('a', 'b', 'c'), 'first')
(('a', 'c', 'c'), 'third')
如何将它扩展到对元组中第二个元素,第一个元素和第三个元素的组合进行排序? E.g。
(('a', 'b', 'c'), 'first')
(('d', 'b', 'c'), 'second')
(('a', 'c', 'c'), 'third')
答案 0 :(得分:4)
只需使用key=lambda tup: (tup[1], tup[0], tup[2])
operator.itemgetter
,甚至更快/更轻松/更好:
from operator import itemgetter
relations_sorted = sorted(relations.keys(), key=itemgetter(1, 0, 2))
答案 1 :(得分:1)
更改为key=lambda tup: (tup[1], tup[0], tup[2])