是否有一种pythonic方法来获取dict中列表中的变量总量?

Dex*_*ter 2 python dictionary list python-2.7

我有一个字典,其中每个键都有一个列表(向量)的项目:

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)
Run Code Online (Sandbox Code Playgroud)

这将打印:

14 # number of items in the 3 dict keys.
Run Code Online (Sandbox Code Playgroud)

除了创建这个"getTotalVectorItems"函数之外,还有更简单的pythonic方法吗?我觉得有一种快速的方法可以做到这一点.

Gar*_*tty 7

您正在寻找带有生成器表达式sum()内置函数:

sum(len(v) for v in items.values())
Run Code Online (Sandbox Code Playgroud)

sum()函数总计给定迭代器的值,生成器表达式生成列表中每个值的长度.

请注意,调用列表向量可能会让大多数Python程序员感到困惑,除非您在问题域的上下文中使用术语向量.