按列表中元素出现的次数对列表进行排序 [英] Sort a list by the number of occurrences of the elements in the list
问题描述
我想按列表中元素的出现次数对列表进行排序.
当我使用这种形式时:
I want to sort a list by the number of occurrences of the elements in the list.
When I use this form:
A=[2,1,3,4,2,2,3]
A.sort(key=lambda x:A.count(x))
print(A)
结果不是我想要的:[2, 1, 3, 4, 2, 2, 3]
.
但是,当我使用sorted
进行书写时:
the result is not what I want: [2, 1, 3, 4, 2, 2, 3]
.
But, when I write like it using sorted
:
B=sorted(A,key=lambda x:A.count(x))
print(B)
结果正确:[1, 4, 3, 3, 2, 2, 2]
.
这种行为的原因是什么?
the result is right: [1, 4, 3, 3, 2, 2, 2]
.
what's the reason for this behavior?
推荐答案
这是故意设计的.在对列表进行排序时,CPython暂时禁止"访问列表,其行为已记录这里:
This is by design and intentional. CPython temporarily "disallows" access to the list while the list is being sorted in place, the behavior is documented here:
CPython实现细节: 在对列表进行排序时, 尝试更改甚至检查列表的效果是 未定义. Python的C实现使列表显示为空 持续时间,如果可以检测到列表,则引发ValueError 在排序过程中发生了变异.
CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.
您可以通过在键功能内打印A
进行检查-您会得到一个空列表:
You can inspect that by printing A
inside the key function - you'll get an empty list:
In [2]: def key_function(x):
...: print(A, x)
...: return A.count(x)
...:
In [3]: A.sort(key=key_function)
([], 2)
([], 1)
([], 3)
([], 4)
([], 2)
([], 2)
([], 3)
但是,如果您对sorted()
执行此操作:
But, if you do that for sorted()
:
In [4]: sorted(A, key=key_function)
([2, 1, 3, 4, 2, 2, 3], 2)
([2, 1, 3, 4, 2, 2, 3], 1)
([2, 1, 3, 4, 2, 2, 3], 3)
([2, 1, 3, 4, 2, 2, 3], 4)
([2, 1, 3, 4, 2, 2, 3], 2)
([2, 1, 3, 4, 2, 2, 3], 2)
([2, 1, 3, 4, 2, 2, 3], 3)
Out[4]: [1, 4, 3, 3, 2, 2, 2]
它也记录在 sort()
实现内部:>
It is also documented inside the sort()
implementation:
/* The list is temporarily made empty, so that mutations performed
* by comparison functions can't affect the slice of memory we're
* sorting (allowing mutations during sorting is a core-dump
* factory, since ob_item may change).
*/.
这篇关于按列表中元素出现的次数对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!