如何在列表中获取最常见的元素(Python)

时间:2017-09-20 08:46:41

标签: python

如何打印前3个字符并计算?

鉴于列表:jiuasdi98237657AJJJa9isd9822jjflkgaaiI

其中,如果格式为list1 = ['j', 'i', 'u', 'a' ... ]

输出:j:6, a:5, i:4

我所做的是降低所有

的情况
 newList = []
 for count in list1:
     newList.append(count.lower())

2 个答案:

答案 0 :(得分:0)

import operator

data = list("kkshdnlsjdhdop;djiee938423jdf")
# This can be a list or a string result will be the same

# Making own counter, easier would be to use the collections.Counter though
counter = {}
for char in set(data):
    counter[char] = data.count(char)

# Getting top 3 counts from the counter
topCount = dict(sorted(counter.items(), key=operator.itemgetter(1), reverse=True)[:3])
print(topCount)
# Output = {'d': 5, 'j': 3, 'k': 2}

使用collections.Counter这很容易:

from collections import Counter
data = ['k', 'k', 's', 'h', 'd', 'n', 'l', 's', 'j', 'd', 'h', 'd', 'o', 'p', ';', 'd', 'j', 'i', 'e', 'e', '9', '3', '8', '4', '2', '3', 'j', 'd', 'f']
print(dict(Counter(data).most_common(3)))
# Output = {'d': 5, 'j': 3, 'k': 2}

答案 1 :(得分:0)

只需使用收集计数器,

from collections import Counter

Counter(i for i in list1 if i.isalpha())

这将为char类型值创建字典。