在Python中,如何获取列表中出现次数最多的内容,并以这种方式对其进行排序?

发布于 2024-10-14 03:22:38 字数 146 浏览 3 评论 0原文

[3, 3, 3, 4, 4, 2]

将是:

[ (3, 3), (4, 2), (2, 1) ]

输出应按最高计数到最低计数排序。在这种情况下,3比2比1。

[3, 3, 3, 4, 4, 2]

Would be:

[ (3, 3), (4, 2), (2, 1) ]

The output should be sorted by highest count first to lowest count. In this case, 3 to 2 to 1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

蓝梦月影 2024-10-21 03:22:38

您可以在 Python 2.7+ 中使用 计数器 (此食谱适用于 2.5+):

from collections import Counter
print Counter([3, 3, 3, 4, 4, 2]).most_common()
# [(3, 3), (4, 2), (2, 1)]

You can use a Counter in Python 2.7+ (this recipe works on 2.5+):

from collections import Counter
print Counter([3, 3, 3, 4, 4, 2]).most_common()
# [(3, 3), (4, 2), (2, 1)]
你好,陌生人 2024-10-21 03:22:38
data = [3, 3, 3, 4, 4, 2]
result = []
for entry in set(data):
    result.append((entry, data.count(entry)))
result.sort(key = lambda x: -x[1])
print result

>>[(3, 3), (4, 2), (2, 1)]
data = [3, 3, 3, 4, 4, 2]
result = []
for entry in set(data):
    result.append((entry, data.count(entry)))
result.sort(key = lambda x: -x[1])
print result

>>[(3, 3), (4, 2), (2, 1)]
九命猫 2024-10-21 03:22:38

尝试使用 collections.Counter:

from collections import Counter
data = [3,4,2,3,4,3]
Counter(data).most_common()

Try using a collections.Counter:

from collections import Counter
data = [3,4,2,3,4,3]
Counter(data).most_common()
明媚如初 2024-10-21 03:22:38

为什么要选择 O(n**2) 算法来执行此操作。 Counter 的替代方案(如果您的值 <2.7)并不太困难

>>> from operator import itemgetter
>>> from collections import defaultdict
>>> L=[3, 3, 3, 4, 4, 2]
>>> D=defaultdict(int)
>>> for i in L:
...     D[i]+=1
... 
>>> sorted(D.items(), key=itemgetter(1), reverse=True)
[(3, 3), (4, 2), (2, 1)]

Why would you choose an O(n**2) algorithm to do this. The alternative to Counter (if you have <2.7) is not too difficult

>>> from operator import itemgetter
>>> from collections import defaultdict
>>> L=[3, 3, 3, 4, 4, 2]
>>> D=defaultdict(int)
>>> for i in L:
...     D[i]+=1
... 
>>> sorted(D.items(), key=itemgetter(1), reverse=True)
[(3, 3), (4, 2), (2, 1)]
聊慰 2024-10-21 03:22:38
def myfun(x,y):
    return x[1]-y[1]

list1 = [3, 3, 3, 4, 4, 2]
s1 = set(list1)
newlist = []
for e in s1:
    newlist.append((e,list1.count(e)))
print sorted(newlist,cmp=myfun)

我想,这就是你所要求的。抱歉,第一次回答太仓促了。但请注意,排序的 cmp 参数在 python3 中不可用

def myfun(x,y):
    return x[1]-y[1]

list1 = [3, 3, 3, 4, 4, 2]
s1 = set(list1)
newlist = []
for e in s1:
    newlist.append((e,list1.count(e)))
print sorted(newlist,cmp=myfun)

I think, this is what you asked for. Sorry for hurry with the first answer. But just note that cmp argument for sorted is not available in python3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文