python dict根据值排序,有两部分,一个是升序,另一个是降序

python dict sort according to the values having two parts , one in ascending and other in descending

我有以下指令:

{'a1': (45, 8.2), 'a2': (80, 3.2), 'a3': (50, 4.2), 'a4': (80, 2.2)}

为了排序,我这样做了:

import operator
sorted_d = sorted(d.items(),key=operator.itemgetter(1),reverse= True)

和sorted_d现在是:

[('a2', (80, 3.2)), ('a4', (80, 2.2)), ('a3', (50, 4.2)), ('a1', (45, 8.2))]

如我所愿:

[('a4', (80, 2.2)), ('a2', (80, 3.2)), ('a3', (50, 4.2)), ('a1', (45, 8.2))]

值的第一部分按降序排列,值的第二部分按升序排列。

有实现预期输出的想法吗?

您需要提供一个元组作为排序依据。 否定要排序的第一个条目以强制降序排序:

sorted(d.items(), key=lambda i: (-i[1][0], i[1][1]))

请注意,reverse=True 参数已消失。

演示:

>>> d = {'a1': (45, 8.2), 'a2': (80, 3.2), 'a3': (50, 4.2), 'a4': (80, 2.2)}
>>> sorted(d.items(), key=lambda i: (-i[1][0], i[1][1]))
[('a4', (80, 2.2)), ('a2', (80, 3.2)), ('a3', (50, 4.2)), ('a1', (45, 8.2))]

我们在这里所做的只是利用 Python 序列按字典顺序排序的事实;如果您比较两个元组,则比较第一个元素,并且仅当它们与第二个位置的元素匹配时才被考虑,依此类推。见 documentation on comparison expressions:

Tuples and lists are compared lexicographically using comparison of corresponding elements. [...] If not equal, the sequences are ordered the same as their first differing elements.

通过提供一个元组作为每个条目的排序值,我们可以提供有关如何对第一个元素相同的项目进行排序的更多信息。

您不能在这里简单地使用 reverse,因为它会在向前排序后反转整个列表,并且它不提供反转子组的选项。否定技巧只是提供从零 到 其他方向的整数,这也会导致排序顺序反转。当第一个元素匹配时,排序继续沿相同的前进方向使用第二个元素。