当我试图从字典中删除一个fox对象时,当它在我的模拟程序中饥饿时,我会得到一个运行时错误,我如何解决这个问题?
我试着使用我在网上发现的其他方法,但我仍然得到同样的错误。
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)发布于 2022-11-10 17:33:36
不确定这是否是复制/粘贴错误,但缩进是不正确的。Main函数下的第10-16行需要缩进。整个Main函数也可能不需要与__init__函数相等,这取决于您想如何使用它。
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。
发布于 2022-11-10 17:34:23
在以下几行:
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())的新列表,并遍历该列表:
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?
https://stackoverflow.com/questions/74392966
复制相似问题