一、Counter的功能介绍
from collections import Counter ,Counter可以对字符串、列表、元祖、字典进行计数,返回一个字典类型的数据,键是元素,值是元素出现的次数。
调用most_common(x) 可以统计出现最多次数的X个元素(从大到小输出)
Counter 可以与其他方法联合操作,输出不一样的结果,还可以做数学运算。
from collections import Counter
str = "hello-python-hello-hadoop"
r1 = Counter(str)
print("返回键与值:", r1)
print("值的总和:", sum(r1.values()))
r2 = r1.most_common(4)
print("---" * 18)
print("从大到小:", r2)
r3 = str.split("-")
print("---" * 18)
print("split分割:", r3)
print("单词统计:", Counter(r3))
二、找出所有重复元素
from collections import Counter
def find_duplicate(str):
c = Counter(str)
print(c)
return list(filter(lambda k: c[k] > 1, c))
str = input("请输入字符串:")
find_duplicate(str)
三、Counter联合统计次数
from collections import Counter
tool = ['pen', 'rule', 'knife', 'sword', 'paper']
stationery = ['pen', 'rule', 'paper']
t = Counter(tool)
s = Counter(stationery)
print("累加输出:", (t+s))
print("--"* 25)
def sum_counter(*data):
if len(data) < 1:
return "输入错误"
mapc = map(Counter, data)
s = Counter([])
print(s)
for ic in mapc:
s += ic
print(s)
return s
sum_counter(t, s, ['pen'], ['rule', 'paper', 'watch'])
|