您的位置:首页 > 编程语言 > Python开发

python 可迭代对象中某元素出现的次数

2020-01-15 11:09 1046 查看

一、可迭代对象中某元素出现的次数

data = [1,2,3,4,5,6,2,3,5,23,5,1,6,7,23,'a','d','f','d','fd','daf','a','xca','a','data']

1、Counter

from collections import Counter
result = Counter(data)

2、+=

result = {}
for i in data:
count = result.get(i, 0)
count += 1
result[i] = count

3、defaultdict

from collections import defaultdict
result = defaultdict(int)
for i in data:
result[i] += 1

4、推导式

result = {x:data.count(x) for x in data}

二、统计同类型的数据

data = {'A':{'a':2, 'b':4, 'c':3},
'B': {'e':2, 'v':4, 'r':3},
'C': {'r':2, 'd':4, 'e':3, 'y':1},
'D': {'t':2, 'x':4, 'w':3},
'E': {'s':2, 'q':4, 'd':3},
'F': {'d':2, 'c':4, 'e':3, 'a':1},
'G': {'x':2, 'z':4},
}

1、+=

result = {}
for _, datas in data.items():
for name, num in datas.items():
count = result.get(name, 0)
count += num
result[name] = count

2、defaultdict

from collections import defaultdict
result = defaultdict(int)
for _, datas in data.items():
for name, num in datas.items():
result[name] += num
  • 点赞
  • 收藏
  • 分享
  • 文章举报
浪子哥学习笔记 发布了13 篇原创文章 · 获赞 0 · 访问量 127 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: