使用list.count使用.sort()就地对列表进行排序不起作用.为什么? [英] Using list.count to sort a list in-place using .sort() does not work. Why?

查看:58
本文介绍了使用list.count使用.sort()就地对列表进行排序不起作用.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按其元素的频率对列表进行排序.

I am trying to sort a list by frequency of its elements.

>>> a = [5, 5, 4, 4, 4, 1, 2, 2]
>>> a.sort(key = a.count)
>>> a
[5, 5, 4, 4, 4, 1, 2, 2]

a不变.但是:

>>> sorted(a, key = a.count)
[1, 5, 5, 2, 2, 4, 4, 4]

为什么该方法不适用于.sort()?

Why does this method not work for .sort()?

推荐答案

您看到的是list.sort的某些 CPython实现细节的结果.再试一次,但是先创建a的副本:

What you see is the result of a certain CPython implementation detail of list.sort. Try this again, but create a copy of a first:

a.sort(key=a.copy().count)
a
# [1, 5, 5, 2, 2, 4, 4, 4]

.sort在内部修改a,因此a.count将产生不可预测的结果.这是

.sort modifies a internally, so a.count is going to produce un-predictable results. This is documented as an implementation detail.

copy调用的作用是创建a的副本,并使用那个列表的count方法作为键.您可以看到一些调试语句会发生什么:

What copy call does is it creates a copy of a and uses that list's count method as the key. You can see what happens with some debug statements:

def count(x):
    print(a)
    return a.count(x)

a.sort(key=count)
[]
[]
[]
...

.sort内部访问时,

a会显示为空列表,而[].count(anything)将是0.这解释了为什么输出与输入相同-谓词都相同(0).

a turns up as an empty list when accessed inside .sort, and [].count(anything) will be 0. This explains why the output is the same as the input - the predicates are all the same (0).

OTOH,sorted创建一个新列表,因此它没有此问题.

OTOH, sorted creates a new list, so it doesn't have this problem.

如果您真的想按频率计数排序,惯用的方法是使用Counter:

If you really want to sort by frequency counts, the idiomatic method is to use a Counter:

from collections import Counter

a.sort(key=Counter(a).get)
a
# [1, 5, 5, 2, 2, 4, 4, 4]

这篇关于使用list.count使用.sort()就地对列表进行排序不起作用.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆