gpt4 book ai didi

python - 按列表中元素的出现次数对列表进行排序

转载 作者:IT老高 更新时间:2023-10-28 20:28:14 31 4
gpt4 key购买 nike

我想按列表中元素出现的次数对列表进行排序。
当我使用这种形式时:

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 写出这样的内容时:

B=sorted(A,key=lambda x:A.count(x))
print(B)

结果是对的:[1, 4, 3, 3, 2, 2, 2].
这种行为的原因是什么?

最佳答案

这是设计和故意的。 CPython 暂时“禁止”访问列表,而列表正在就地排序,行为是 documented here :

CPython implementation detail: While a list is being sorted, theeffect of attempting to mutate, or even inspect, the list isundefined. The C implementation of Python makes the list appear emptyfor the duration, and raises ValueError if it can detect that the listhas been mutated during a sort.

您可以通过在 key 函数中打印 A 来检查 - 您将得到一个 空列表:

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() 这样做:

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() 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).
*/.

关于python - 按列表中元素的出现次数对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42026581/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com