我对python非常陌生,正在编写一个简单的游戏,我只是想找到一种方法来计算一个单词在包含其他列表/字典的字典中的迭代次数。你知道吗
我已经找到了很多文章来真正-接近-解释它(例如,得到键,但不是值),但我找不到我要找的东西。我也是个哑巴,就是这样。你知道吗
我还遇到过一些人,他们用python3中存在的一个函数来解释这一点,但在python2中还没有一个适合我的函数。你知道吗
我想数一数“哺乳动物”这个词在最大的字典里出现的次数。你知道吗
"""Bestiaries"""
levelonebestiary = {}
levelonebestiary["Babychick"] = [1, 10, "bird"]
levelonebestiary["Squirrel"] = [2, 15, "mammal"]
levelonebestiary["Washcloth"] = [0, 1, "cloth"]
leveltwobestiary = {}
leveltwobestiary["Large Frog"] = [3, 20, "amphibian"]
leveltwobestiary["Raccoon"] = [5, 15, "mammal"]
leveltwobestiary["Pigeon"] = [4, 20, "bird"]
nightmarebestiary = {}
nightmarebestiary["pumanoceros"] = [25, 500]
grandbestiary = [levelonebestiary, leveltwobestiary, nightmarebestiary]
谢谢你的帮助!你知道吗
像这样的东西应该能奏效!你知道吗
实现计数的两种方法。基本上是一样的,但第二个表达为理解。
iteritems
生成这个python2代码,但是当您知道您将只使用python3时,请将其更改为items
。你知道吗迭代列表,然后每个包含的dict。然后您可以检查每个dict条目中的值,看看它们是否包含字符串“哺乳动物”。您可能希望进一步限制它,以检查列表中只有第3个元素等于“哺乳动物”。你知道吗
变量
count
和count2
保存这些值。这假设“哺乳动物”只出现在字典值列表中,而不出现在字典键中。你知道吗或者完全避免使用
iteritems
,因为我们并不真正关心密钥,而且您有一个py2/3解决方案。你知道吗相关问题 更多 >
编程相关推荐