在 Python 中,为什么以下代码在列表已排序和未排序时给出错误答案?

In Python why does the following code give incorrect answers when the list is sorted and list is un-sorted?

我正在尝试根据元素出现的频率对列表进行排序。但是当列表排序列表未排序时,我得到两个不同的答案。 请看下面的代码段。

谁能解释一下原因。谢谢。

from collections import Counter
l = [1,1,0,0,5,2,5,5,3,4,33,0]
# Stores the frequency of each element as {elem: freq}
c = Counter(l)

# Sorting the list based on the frequency of the elements
lst1 = sorted(l, key=lambda x: -c[x])
# lst1: [0, 0, 5, 5, 5, 0, 1, 1, 2, 3, 4, 33]

l.sort()
# Sorting the list based on the frequency of the elements
lst2 = sorted(l, key=lambda x: -c[x])
# lst2: [0, 0, 0, 5, 5, 5, 1, 1, 2, 3, 4, 33]

两个结果都是正确的。

由于 c[0]c[5] 都出现了,计算结果为 3(在本例中),并且在这两种情况下单独使用该数字作为排序键,排序算法会将两个整数视为“相等”,并仅根据遇到它们的顺序对它们进行排序。

查看documentation of sorted告诉我们这是排序算法的一个特点:

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal

如果您想按整数的值排序,以防两次出现相同,您可以将排序功能扩展到 return 个元组,例如:

lst = sorted(l, key=lambda x: (-c[x], x))
# lst: [0, 0, 0, 5, 5, 5, 1, 1, 2, 3, 4, 33]