首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在迭代字典时从字典中删除特定的fox对象

如何在迭代字典时从字典中删除特定的fox对象
EN

Stack Overflow用户
提问于 2022-11-10 17:18:40
回答 2查看 21关注 0票数 0

当我试图从字典中删除一个fox对象时,当它在我的模拟程序中饥饿时,我会得到一个运行时错误,我如何解决这个问题?

我试着使用我在网上发现的其他方法,但我仍然得到同样的错误。

代码语言:javascript
复制
import random

class Simulation:
    def __init__(self):
        self.Foxes = {}
        for i in range(100): # Creates 100 foxes
            self.Foxes[i] = Fox()

        def Main(self):
            for i in range(100): # Forages for each fox and checks for starvation
                for i in self.Foxes.keys(): 
                    self.Foxes[i].Forage()
                    if self.Foxes[i].Hunger >= self.Foxes[i].HungerMaximum:
                        self.Foxes.pop(i)

            print("There are " + str(len(self.Foxes)) + " foxes remaining.")

class Animal:
    def __init__(self): 
        self.Age = 0
        self.HungerMaximum = 50
        self.Hunger = 0
        self.ForagingChance = 20

    def Forage(self):
        if random.randint(1,self.ForagingChance) == self.ForagingChance:
            if self.Hunger > 10:
                self.Hunger = self.Hunger - 10
        else:
            self.Hunger = self.Hunger + 10
        
class Fox(Animal):
    def __init__(self):
        Animal.__init__(self)
EN

回答 2

Stack Overflow用户

发布于 2022-11-10 17:33:36

不确定这是否是复制/粘贴错误,但缩进是不正确的。Main函数下的第10-16行需要缩进。整个Main函数也可能不需要与__init__函数相等,这取决于您想如何使用它。

代码语言:javascript
复制
class Simulation:
    def __init__(self):
        self.Foxes = {}
        for i in range(100): # Creates 100 foxes
            self.Foxes[i] = Fox()

    def Main(self):
        for i in range(100): # Forages for each fox and checks for starvation
            for i in self.Foxes.keys(): 
                self.Foxes[i].Forage()
                if self.Foxes[i].Hunger >= self.Foxes[i].HungerMaximum:
                    self.Foxes.pop(i)

            print("There are " + str(len(self.Foxes)) + " foxes remaining.")

正如另一个答案所提到的,在迭代字典的同时修改字典,您也将得到一个RuntimeError: dictionary changed size during iteration

票数 0
EN

Stack Overflow用户

发布于 2022-11-10 17:34:23

在以下几行:

代码语言:javascript
复制
            for i in self.Foxes.keys(): 
                self.Foxes[i].Forage()
                if self.Foxes[i].Hunger >= self.Foxes[i].HungerMaximum:
                    self.Foxes.pop(i)

通过在self.Foxes.keys()上的for循环中调用self.Foxes.keys(),您将在字典元素的迭代过程中更改字典的大小。这在Python中是不允许的,它将生成一个RuntimeError

为了克服这个限制,创建一个包含self.Foxes.keys() -> list(self.Foxes.keys())的新列表,并遍历该列表:

代码语言:javascript
复制
            for i in list(self.Foxes.keys()): 
                self.Foxes[i].Forage()
                if self.Foxes[i].Hunger >= self.Foxes[i].HungerMaximum:
                    self.Foxes.pop(i)

也见这里的答案:How do I delete items from a dictionary while iterating over it?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74392966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档