0

我想找到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

有没有更干净或更快的方法来编写该代码?

4

3 回答 3

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})
于 2013-08-31T22:23:46.337 回答
1

使用 a 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是 key in是一种不好的方法tags,特别是因为它在任何情况下都会失败,在布尔上下文中值可能被视为 false 的情况下。首选以下:

if t in tags:
于 2013-08-31T22:23:41.043 回答
0

collections.Counter非常适合计算事物。

于 2013-08-31T22:23:37.697 回答