|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
找出序列中出现次数最多的元素
问题描述:
我们有有一个序列,想找出里面出现次数最多的元素
一、from collections import Counterfrom collections import Counter
words = ["if", "you", "and", "me", "if", "I",
"love", "cat", "dog", "if", "love", "me", "you", "if", "me", "dog"]
word_counts = Counter(words)
temp = Counter(words)
# 找出最多的三个
top_three = word_counts.most_common(4) # 参数
print(word_counts)
print(top_three)
Counter({'if': 4, 'me': 3, 'dog': 2, 'you': 2, 'love': 2, 'and': 1, 'I': 1, 'cat': 1})
[('if', 4), ('me', 3), ('dog', 2), ('you', 2)]
字典的顺序和其在原列表顺序一致
二、字典中数据更新new_word = ["if", "you", "and", "I", "love"]
# 数据的更新
# 迭代法
for word in new_word:
word_counts[word] += 1
print(word_counts)
# 内置方法
word_counts.update(new_word)
print(word_counts)
Counter({'if': 5, 'you': 3, 'me': 3, 'love': 3, 'and': 2, 'I': 2, 'dog': 2, 'cat': 1})
Counter({'if': 6, 'you': 4, 'love': 4, 'and': 3, 'me': 3, 'I': 3, 'dog': 2, 'cat': 1})
三、两个Counter对象间的运算temp["mq"] = 1
print(temp)
a = temp + word_counts
print(a)
b = temp - word_counts
print(b)
c = word_counts - temp
print(c)
集合加减法
temp ({'if': 4, 'me': 3, 'you': 2, 'love': 2, 'dog': 2, 'and': 1, 'I': 1, 'cat': 1,'mq': 1})
Counter({'if': 10, 'you': 6, 'me': 6, 'love': 6, 'and': 4, 'I': 4, 'dog': 4, 'cat': 2})
Counter({'mq': 1})
Counter({'if': 2, 'you': 2, 'and': 2, 'I': 2, 'love': 2})
|
|