Python collections.Counter()用法
Counter 计数器,最主要的作用就是计算“可迭代序列中”各个元素(element)的数量
统计“可迭代序列”中每个元素的出现的次数
#首先引入该方法
from collections import Counter
# 对列表作用
list_01 = [1, 9, 9, 5, 0, 8, 0, 9]
print(Counter(list_01)) # Counter({9: 3, 0: 2, 1: 1, 5: 1, 8: 1})
# 对字符串作用
temp = Counter('abcdeabcdabcaba')
print(temp) # Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
# 以上其实是两种使用方法,一种是直接用,一种是实例化以后使用,如果要频繁调用的话,显然后一种更简洁
Counter(a)-Counter(b)
from collections import Counter
a = 'abbacde'
b = 'abcdefg'
print(Counter(a)) # Counter({'a': 2, 'b': 2, 'c': 1, 'd': 1, 'e': 1})
print(Counter(b)) # Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1})
print(Counter(a)-Counter(b)) # Counter({'a': 1, 'b': 1})
print(Counter(b)-Counter(a)) # Counter({'f': 1, 'g': 1})
# Counter(a)-Counter(b)= Counter({'a': 2-1, 'b': 2-1, 'c': 1-1, 'd': 1-1, 'e': 1-1})
# =Counter({'a': 1, 'b': 1, 'c': 0, 'd': 0, 'e': 0})=Counter({'a': 1, 'b': 1})
# Counter(b)-Counter(a)= Counter({'a': 1-2, 'b': 1-2, 'c': 1-1, 'd': 1-1, 'e': 1-1, 'f': 1, 'g': 1})
# =Counter({'a': -1, 'b': -1, 'c': 0, 'd': 0, 'e': 0, 'f': 1, 'g': 1})=Counter({'f': 1, 'g': 1})
# Counter(b)-Counter(a)中的某字符<=0时去掉该字符
赎金信(字符串a是否能被字符串b中字符的组成)
# 给你一个赎金信 (ransomNote) 字符串和一个杂志(magazine)字符串,判断 ransomNote 能不能由 magazines 里面的字符构成。
# 如果可以构成,返回 true ;否则返回 false 。
# magazine 中的每个字符只能在 ransomNote 中使用一次。
from collections import Counter
ransomNote = 'ascx1234'
magazine = 'asxzc1234567asx'
if len(ransomNote) > len(magazine):
print(False)
print(not Counter(ransomNote) - Counter(magazine))
# Counter(ransomNote) 统计ransomNote中字出现的次数
# Counter(magazine) 统计magazine中字出现的次数
# Counter(ransomNote) - Counter(magazine))的结果为Counter类型
# 当Counter(ransomNote) - Counter(magazine)为空时证明ransomNot中的字符能在magazine找到
# Counter类型为空时转换成布尔值为False,根据题意可知杂志中的字符可以构成赎金信返回True,所以要在前面加not