【发布时间】:2013-02-12 20:17:44
【问题描述】:
我有一本字典,其中每个键都有一个项目列表(向量):
from collections import defaultdict
dict = defaultdict(list)
dict[133] = [2,4,64,312]
dict[4] = [2,3,5,12,45,32]
dict[54] = [12,2,443,223]
def getTotalVectorItems(items):
total = 0
for v in items.values():
total += len(v)
return total
print getTotalVectorItems(dict)
这将打印:
14 # number of items in the 3 dict keys.
除了创建这个“getTotalVectorItems”函数之外,还有更简单的 Pythonic 方法吗?我觉得已经有一种快速的方法可以做到这一点。
【问题讨论】:
-
sum(map(len,dic.values())),不要使用dict作为变量名。 -
您在这里使用
defaultdict是否有原因(可能在您省略的代码中)?您的代码同样适用于d = {}; d[133] = [2,4,64,312]等。 -
或者,更好的是:
d = {133: [2, 4, 64, 312], 4: [2, 3, 5, 12, 45, 32], 54: [12, 2, 443, 223]}- 这不是 Java,我们有 dict 文字。 -
@AshwiniChaudhary 抱歉,我的伪代码写得不好。我会给你的代码一个镜头。我使用 defaultdict 因为它是使用列表作为 dict 键值的唯一方法(或者我被告知)。
-
@lattyware 哦,谢谢,我没有意识到我能做到。
标签: python list dictionary python-2.7