Counter类(计数器)

Counter类返回一个字典,统计每个元素出现次数,可以更新

  1. import collections
  2. obj = collections.Counter(['11','22'])
  3. obj.update(['22','55'])
  4. print(obj)
  5. #输出:Counter({'22': 2, '11': 1, '55': 1})

all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。

  1. class Solution:
  2. def countCharacters(self, words: List[str], chars: str) -> int:
  3. count=collections.Counter(chars)
  4. sumlen=0
  5. for word in words:
  6. c=collections.Counter(word)
  7. #list类型作为参数
  8. if all([count[i]>=c[i] for i in word]):
  9. sumlen+=len(word)
  10. return sumlen

dict.item()返回字典键值对组成的元组



学习笔记      Python

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!