python精要(81)-collections容器类型(1)-统计相同的值
生活随笔
收集整理的這篇文章主要介紹了
python精要(81)-collections容器类型(1)-统计相同的值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Counter是一個容器,可統計相同的值有多少個,可視為:將值作為鍵,數量作為值的字典
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import collections x=[1,2,3,11,22,33,1,2,3,4,22] y=['a','b','c','d','a','c'] z={'a':3,'b':5,2:8} print(collections.Counter(x)) print(collections.Counter(y)) zCounter=collections.Counter(z) zCounter.update(y) print(zCounter) zCounter.update(x) print(zCounter)結果如下:
Counter({1: 2, 2: 2, 3: 2, 22: 2, 11: 1, 33: 1, 4: 1}) Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1}) Counter({2: 8, 'b': 6, 'a': 5, 'c': 2, 'd': 1}) Counter({2: 10, 'b': 6, 'a': 5, 'c': 2, 1: 2, 3: 2, 22: 2, 'd': 1, 11: 1, 33: 1, 4: 1})使用字典API
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import collections x=[1,2,3,11,'a',33,1,2,'b','b',22] z={'a':3,'b':5,2:8} zCounter=collections.Counter(z) zCounter.update(x) for key,val in zCounter.items():print(key,val) print("----------") for key in zCounter.keys():print(key,zCounter[key])結果如下:
a 4 b 7 2 10 1 2 3 1 11 1 33 1 22 1 ---------- a 4 b 7 2 10 1 2 3 1 11 1 33 1 22 1總結
以上是生活随笔為你收集整理的python精要(81)-collections容器类型(1)-统计相同的值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java中replace、replace
- 下一篇: SpringAOP Aspect注解实现