【问题标题】:How do you count elements of a list that's inside a dictionary? [duplicate]你如何计算字典中列表的元素? [复制]
【发布时间】:2021-04-05 22:17:47
【问题描述】:

我正在学习 python,需要一些使用字典的技巧。请看下面的代码。我尝试使用if word in filename.values()if filename[word] 检查字典中是否存在该单词,但它不起作用。我想检查一下,如果可能的话,计算单词出现在字典内这些列表中的总次数。请指教!

files = {"f1": ["cat", "dog", "mouse"],
         "f2": ["rat", "elephant", "tiger"]}

word = "dog"

for filename in files:
    if word in filename.values():
        print(True)
    else:
        print(False)

【问题讨论】:

  • for filename in files 将遍历字典的键。 key,value 对需要files.items()
  • 不,因为它只计算字典的键。
  • for key, value in files.items(): if word in value: print(True) else: print(False)
  • any(word in i for i in files.values()) 检查是否在任何列表中。

标签: python


【解决方案1】:

这是你所期望的?

files = {"f1": ["cat", "dog", "mouse"],
         "f2": ["rat", "elephant", "tiger", "dog"]}

word = "dog"
counter = 0

for values in files.values():
    if word in values:
        print(True)
        counter +=1
    else:
        print(False)

print(counter)

【讨论】:

  • 如果我在“f1”中有两个“狗”,它应该算两次。
  • 用那个替换计数器行:counter += values.count(word)
猜你喜欢
  • 2016-02-27
  • 2022-01-10
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 2021-12-03
相关资源
最近更新 更多