计算嵌套在其中的列表的字典中字符串的迭代次数

时间:2017-05-24 01:16:35

标签: python list dictionary

我对python非常陌生并且正在编写一个简单的游戏,我只是想找到一种方法来计算包含其他列表/词典的字典中单个单词的迭代次数。

我发现很多文章真的 - 关闭 - 解释它(例如获取键而不是值),但我找不到我正在寻找的东西。我也很笨,所以就是这样。

我也遇到过那些使用Python 3中存在的函数解释过这个问题的人,但是在Python 2中没有任何东西适用于我。

我想计算“哺乳动物”一词出现在最大字典(名为grandbestiary)中的次数。

"""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]

感谢您的帮助!

4 个答案:

答案 0 :(得分:0)

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]

mammal_count = 0
# iterate through all bestiaries in your list
for bestiary in grandbestiary:
    # iterate through all animals in your bestiary
    for animal in bestiary:
        # get the list (value) attached to each aniaml (key)
        animal_description = bestiary[animal]
        # check if "mammal" is in our array (value)
        if "mammal" in animal_description:
            mammal_count += 1

print (mammal_count)

答案 1 :(得分:0)

实现计数的两种方法。基本上是一样的东西,但第二个表达为理解。 iteritems生成这个python 2代码,但当你知道你将只使用python 3时,将它改为items

迭代列表然后每个包含dict。然后你可以检查每个dict条目中的值,看它们是否包含字符串“哺乳动物”。您可能希望进一步限制它以检查只有列表的第3个元素等于“哺乳动物”。

count = 0
for b in grandbestiary:
    for _, v in b.iteritems():
        if "mammal" in v:
            count += 1

count2 = sum("mammal" in v for b in grandbestiary for _, v in b.iteritems())

变量countcount2包含值。这假设“哺乳动物”仅出现在词典值列表中,而不出现在词典键中。

或者完全避免使用iteritems,因为我们并不关心密钥而你有py2 / 3解决方案。

count3 = sum("mammal" in v for b in grandbestiary for v in b.values())

答案 2 :(得分:0)

这样的事情应该可以解决问题!

numOfMamals = 0
# Iterate over each bestiary
for bestiary in grandbestiary:
    # Snag each key string in the bestiary
    for key in bestiary:
        # Look at every item in the bestiary
        for item in bestiary[key]:
            if item == "mammal":
                numOfMamals = numOfMamals + 1

print numOfMamals

答案 3 :(得分:0)

我会使用简短的语法:

sum(1 for bestiary in grandbestiary if any("mammal" in l for l in bestiary.values()))