Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在词典中找到列表长度的总和?_Python_List_Dictionary_Sum - Fatal编程技术网

Python 如何在词典中找到列表长度的总和?

Python 如何在词典中找到列表长度的总和?,python,list,dictionary,sum,Python,List,Dictionary,Sum,在中,您可以使用以下格式的数据集: dataset = { "one" : { "a" : [ 0, 1, 2 ], "b" : [ 0,10,20 ] }, "two" : { "a" : [ 0, 1 ], "b" : [ 0 ] } } 我正在寻找一种快速的方法来计算所有“a”列表的长度总和(最终“b”也是如此) 因此,对于上述数据集,我希望总和为5(因为“一”[a]有3个成员,“二”[a]有2个成员,3+2通常是5) 我原以为这样做就可以了,但我得到了意想不到的结果(错误的数字

在中,您可以使用以下格式的数据集:

dataset = {
  "one" : { "a" : [ 0, 1, 2 ], "b" : [ 0,10,20 ] },
  "two" : { "a" : [ 0, 1 ], "b" : [ 0 ] }
}
我正在寻找一种快速的方法来计算所有“a”列表的长度总和(最终“b”也是如此)

因此,对于上述数据集,我希望总和为5(因为“一”[a]有3个成员,“二”[a]有2个成员,3+2通常是5)

我原以为这样做就可以了,但我得到了意想不到的结果(错误的数字):


我想这会依次得到“1”和“2”,每一个都会查到“a”的长度。然后,它将计算所有长度的总和。没有,我应该使用什么?

您只对每个级别的值感兴趣,所以只需迭代这些值:

>>> dataset = {
  "one": {"a": [0, 1, 2], "b": [0, 10, 20]},
  "two": {"a": [0, 1], "b": [0]}
}
>>> sum(len(lst) for dct in dataset.values() for lst in dct.values())
9
对于嵌套字典中的特定键:

>>> key = 'a'
>>> sum(len(dct[key]) for dct in dataset.values())
5
或获取多个键的计数:

>>> {key: sum(len(dct[key]) for dct in dataset.values()) for key in 'ab'}
{'a': 5, 'b': 4}

可以使用以下生成器表达式:

>>> sum(len(v['a']) for k, v in dataset.items())
5
将itertools用于Python 2:

from itertools import imap,izip
a , b = imap(sum, izip(*((len(d["a"]),len(d["b"])) for d in dataset.itervalues())))

print(a,b)
5 4
如果可能存在不存在的密钥,请使用dict.get:

a, b = imap(sum, izip(*((len(d.get("a", [])), len(d.get("b",[]))) for d in dataset.itervalues())))
from itertools import imap,izip
a , b = imap(sum, izip(*((len(d["a"]),len(d["b"])) for d in dataset.itervalues())))

print(a,b)
5 4
a, b = imap(sum, izip(*((len(d.get("a", [])), len(d.get("b",[]))) for d in dataset.itervalues())))