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

2024-04-25 03:56:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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]

谢谢你的帮助!你知道吗


Tags: 方法函数游戏列表字典文章单词次数
3条回答
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)

像这样的东西应该能奏效!你知道吗

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

实现计数的两种方法。基本上是一样的,但第二个表达为理解。iteritems生成这个python2代码,但是当您知道您将只使用python3时,请将其更改为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())

相关问题 更多 >