【问题标题】:getting the Length of all lists in a dictionary获取字典中所有列表的长度
【发布时间】:2022-11-13 06:13:27
【问题描述】:
listdict = {
'list_1' : ['1'],
'list_2' : ['1','2'],
'list_3' : ['2'],
'list_4' : ['1', '2', '3', '4']
}
print(len(listdict))
例如,这是我的代码。我希望它打印:
8
如您所见,我已经尝试了 length 但它打印 4 当然是列表的数量,但我希望它打印
列表中的项目数量。有没有一种方法可以让我用一个语句来做到这一点,而不是单独做所有的事情?提前致谢。
我尝试使用 len(dictionaryname) 但这没有用
【问题讨论】:
标签:
python
list
dictionary
【解决方案1】:
您的字典中有 4 个列表作为值,因此您必须对长度求和:
print(sum(map(len, listdict.values())))
印刷:
8
【解决方案2】:
考虑使用另一个内置函数sum(len 是一个内置函数):
>>> listdict = {
... 'list_1' : ['1'],
... 'list_2' : ['1','2'],
... 'list_3' : ['2'],
... 'list_4' : ['1', '2', '3', '4']
... }
>>> sum(len(xs) for xs in listdict.values())
8
顺便说一句,由于python使用duck typing在Python中使用Hungarian naming作为变量有点susngl...