Python:获取列表中最常见的项目 [英] Python: Get most frequent item in list

查看:148
本文介绍了Python:获取列表中最常见的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组列表,我想得到最频繁出现的元组,但是如果有联合赢家,它应该随机选择它们。



($ 1,2),(3,4)]
/ code>

所以我想要随机返回上述列表的内容(1,2)或(3,4) / p>

解决方案

您可以先使用Counter来查找最重复的元组。然后找到所需的元组并最终随机化并获得第一个值。

  from集合import counter 
import random

tups = [(1,2),(3,4),(5,6),(1,2),(3,4)]
lst =计数器(tups)。如果我[1] == highest_count]
,那么我将在最后一次进入i [1] most_common()
highest_count = max([i [1] for i in lst])
values = [i [0] random.shuffle(values)
print values [0]


I've got a list of tuples, and I want to get the most frequently occurring tuple BUT if there are "joint winners" it should pick between them at random.

tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]

so I want something that would return either (1,2) or (3,4) at random for the above list

解决方案

You can first use Counter to find the most repeated tuple. Then find the required tuples and finally randomize and get the first value.

from collections import Counter
import random

tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
lst = Counter(tups).most_common()
highest_count = max([i[1] for i in lst])
values = [i[0] for i in lst if i[1] == highest_count]
random.shuffle(values)
print values[0]

这篇关于Python:获取列表中最常见的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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