热线电话:13121318867

登录
2019-03-07 阅读量: 568
python如何输出元组发生次数?

Counter Package的most_common功能。

这可能是我曾经使用过的最有用的函数,在编写任何python代码时它始终处于我的脑海中。此函数分析列表/字符串,并有助于根据列表/字符串的出现次数按降序返回前n个实体,其中n是程序员指定的数字。返回各个实体及其在元组中的出现次数,可以在需要时轻松地进行参考/打印。

# Code to find top 3 elements and their counts

# using most_common

from collections import Counter

arr = [1, 3, 4, 1, 2, 1, 1, 3, 4, 3, 5, 1, 2, 5, 3, 4, 5]

counter = Counter(arr)

top_three = counter.most_common(3)

print(top_three)

输出:

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

输出元组清楚地表明1发生了5次,3发生了4次,4发生了3次。

0.7068
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子