2 回答
TA贡献1811条经验 获得超4个赞
您可以通过将子列表映射到函数来获取子列表的长度len
,然后通过将生成的长度序列传递给函数来将它们相加sum
:
sum(map(len, mydict.values()))
TA贡献1824条经验 获得超5个赞
如果你想用循环保留它,你可以这样做:
mydict = {
'apple': [['1', '00:00:03,950'], # 1
['1', '00:00:03,950'], # 2
['9', '00:00:24,030'], # 3
['11', '00:00:29,640']], # 4
'banana': [['20', '00:00:54,449']], # 5
'cherry': [['14', '00:00:38,629']], # 6
'orange': [['2', '00:00:06,840'], # 7
['2', '00:00:06,840'], # 8
['3', '00:00:09,180'], # 9
['4', '00:00:10,830']], # 10
}
n_fruits = 0
for fruit, occurences_of_fruit in mydict.items():
# increment n_fruits by the number of occurence of the fruit
# BTW occurences_of_fruit and mydict[fruit] are the same thing
n_fruits += len(occurences_of_fruit)
print(n_fruits) # 10
添加回答
举报