获取Python中二维列表中存储的特定字典值的数量

我有一个字典,其中包含水果作为键和一个二维列表,其中包括行号和时间戳,其中水果名称作为值出现在转录文件中。需要二维列表是因为水果在文件中出现多次,我需要考虑每次出现的情况。字典看起来像这样:


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

}

现在,我想打印所有水果的总数,所以我想要的解决方案是10。因此,我想计算值的数量,但不是每个单个列表项的数量,不过……只是整个列表的数量,可以这么说(请参阅应该澄清我的意思的注释)。


为此,我尝试了:


print(len(mydict.values()))

但这段代码行只给出了数字 4 作为结果。


以下代码对我也不起作用:


count = 0

for x in mydict: 

    if isinstance(mydict[x], list): 

        count += len(mydict[x]) 

print(count) 

有谁知道如何获得 10 号吗?


繁花不似锦
浏览 66回答 2
2回答

波斯汪

您可以通过将子列表映射到函数来获取子列表的长度len,然后通过将生成的长度序列传递给函数来将它们相加sum:sum(map(len, mydict.values()))

沧海一幻觉

如果你想用循环保留它,你可以这样做: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 = 0for 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python