我想在多维数组中找到tags
的数量。我是这样做的:
l['users']
是我的数据(数组)
tags = {}
for u in l['users']:
for p in u['photos']:
for t in p['tags']:
if tags.get(t):
tags[t] +=1
else:
tags[t] = 1
有没有更清晰或更快的方法来编写该代码?
答案 0 :(得分:3)
使用collections.Counter()的快速和pythonic单线解决方案如何:
Counter是用于计算可哈希对象的dict子类。它是一个 无序集合,其中元素存储为字典键和 他们的计数存储为字典值。
Counter(t for u in l['users'] for p in u['photos'] for t in p['tags'])
样本:
from collections import Counter
l = {'users': [{'photos': [{'tags': [1,2,3,4,5]}, {'tags': [3,4,5]}]},
{'photos': [{'tags': [1]}, {'tags': [2,3,4,5]}]}]}
tags = Counter(t for u in l['users'] for p in u['photos'] for t in p['tags'])
print tags # prints Counter({3: 3, 4: 3, 5: 3, 1: 2, 2: 2})
答案 1 :(得分:1)
使用collections.defaultdict(int)
,0
将使用import collections
tags = collections.defaultdict(int)
for u in l['users']:
for p in u['photos']:
for t in p['tags']:
tags[t] +=1
作为任何尚未拥有的密钥的默认值:
if tags.get(t)
此外,t
是检查tags
是否为if t in tags:
中的密钥的错误方法,尤其是因为它在任何可能被视为错误的上下文中失败布尔上下文。喜欢以下内容:
{{1}}
答案 2 :(得分:0)
collections.Counter适合计算事物。