python中的collections.Counter()

力扣题目:

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        if len(ransomNote)>len(magazine):
            return False
        return not collections.Counter(ransomNote) - collections.Counter(magazine)

 return not collections.Counter(ransomNote) - collections.Counter(magazine)

这句代码中,最后返回值是Ture或False

用collections.Counter(dict)实现

一些相关知识点下文会介绍。

【字典】类型也可以相加减,用collections.Counter(dict)实现,但结果会自动舍掉value值<=0的dict.items()

示例如下:


字典的相加减操作需要用到python内置函数class:collections.Counter([iterable-or-mapping])

#加入有两个字典dict如下:
 
x = {'a': 1, 'b': 2, 'c': 3}
y = {'a': 3, 'b': 1, 'd': 5}

# 相加操作
re_1 = Counter(x) + Counter(y)
print(re_1)
 
# 相减操作
re_2 = Counter(x) - Counter(y)
print(re_2)


输出结果如下:

Counter({'a': 4, 'b': 3, 'c': 3, 'd': 5})
Counter({'b': 1, 'c': 3})


【在结果中,a不见了,是因为输出会忽略掉结果为零或者小于零的计数。】 

如果对Counter其它内容有兴趣的,可以查看下面的参考链接。
参考链接:https://docs.python.org/zh-cn/3/library/collections.html#collections.Counter

not 用法

除了传统的not 1(True)=False,not 0(False)=True外,空列表[] 字典dict()(字典一般不能为空,这里可以用defaultdict()/collections.Counter(dict)中,为空时返回默认值) 数组[]等都为False 可以用not判断

举例 not []=true
 

猜你喜欢

转载自blog.csdn.net/weixin_51472673/article/details/127258143