除我一直希望city [0]保持感染状态外,我正在编写感染和治愈城市的功能。所有城市都在列表中。
def sim_step(cities , p_spread , p_cure):
for city in cities:
if city[1] == True and numpy.random.rand() < p_spread:
zombify(my_world , cities[numpy.random.randint(city[3])])
if city[1] == False and numpy.random.rand() < p_cure:
cure(my_world , cities[numpy.random.randint(city[3])])
答案 0 :(得分:2)
您可以这样做:
def sim_step(cities , p_spread , p_cure):
for city in cities[1:]:
if city[1] == True and numpy.random.rand() < p_spread:
zombify(my_world , cities[numpy.random.randint(city[3])])
if city[1] == False and numpy.random.rand() < p_cure:
cure(my_world , cities[numpy.random.randint(city[3])])
区别在这里:cities[1:]
。这称为切片操作。要了解更多信息,请阅读this answer。
答案 1 :(得分:0)
用这种命名方法很难理解。
但是,据我了解,您的问题是在浏览城市列表时始终收集第一个元素。
我建议使用枚举方法,以便您可以同时浏览元素索引,元素本身
枚举方法允许遍历索引列表和列表元素。
def sim_step(cities , p_spread , p_cure):
for index,city in enumerate(cities):
if city[1] == True and numpy.random.rand() < p_spread:
zombify(my_world , cities[numpy.random.randint(city[3])])
if city[1] == False and numpy.random.rand() < p_cure:
cure(my_world , cities[numpy.random.randint(city[3])])
if index == 0:
remain_infected()
在此处查看有关枚举方法的更多信息: https://docs.python.org/3/library/functions.html#enumerate
答案 2 :(得分:0)
据我了解,您只需要确保不会治愈第一个城市(城市[0])即可。
...
if city[1] == False and numpy.random.rand() < p_cure:
idx = numpy.random.randint(city[3])
if idx == 0:
continue
cure(my_world , cities[idx])