collections.Counter 冷不防 2022-11-18 01:51 124阅读 0赞 Counter是dict子类,用于计数可哈希的对象。这是一个无序的容器,元素被作为字典的key存储,它们的计数作为字典的value存储。 from collections import Counter cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: cnt[word] += 1 print cnt 输出结果: Counter(\{‘blue’: 3, ‘red’: 2, ‘green’: 1\}) from collections import Counter color_list = ['red', 'blue', 'red', 'green', 'blue', 'blue'] cnt = Counter(color_list ) # cnt.clear() 清空哈希字典 print(cnt) 输出结果: Counter(\{‘blue’: 3, ‘red’: 2, ‘green’: 1\}) 参考: https://blog.csdn.net/qq\_29678299/article/details/89975667
还没有评论,来说两句吧...