If else 语句追加到 for 循环中的列表

If else statement append to list in for loop

我想将乌龟 'person' 添加到列表 'infected_people',但出现错误 'TurtleGraphicsError: bad color string: red'。

如何将 'person' 添加到列表 'infected_people' 而不会出现错误。

我是编程新手,如果我的解释不清楚,请见谅。


infected_people = []

i = 0
while i < 30: #number of steps (time)
  for person in people: 
      random_walk(30, 400)
      i + 1
      for infected_person in infected_people: 
          if person.distance(infected_person) < 30: 
              person.color("red")
              infected_people.append(person) 


这是我的代码的另一部分:

import turtle
import random

wn = turtle.Screen()

def person_characteristics(): 
    for person in people:
        person.penup()
        person.shape("circle")
        person.shapesize(0.2)
        x = random.randint(-200, 200)
        y = random.randint(-200, 200)
        person.setpos(x, y)
        person.speed(0)
        turtle.update()
    return person


def population(population_size):
    turtle.update()
    people = []
    for _ in range(population_size):
        people.append(turtle.Turtle())
    return people

def person_characteristics(): 
    for person in people:
        turtle.update()
        person.penup()
        person.shape("circle")
        person.shapesize(0.2)
        person.speed(0)
        x = random.randint(-200, 200)
        y = random.randint(-200, 200)
        person.setpos(x, y)
    return person

def random_walk(step_size, area_size):
    person.clear()
    count = 0
    while count < 1:
        count += 1
        if (-area_size < person.xcor() <area_size) and (-area_size < person.ycor() <area_size):
            person.right(random.randint(0,360))
            person.forward(step_size)
        else:
            person.right(180)
            person.forward(step_size)
    turtle.update()

people = population(50)
person = person_characteristics()

def infect_random(people):
    infected = random.choice(people)
    infected.color("red")
    return infected

infected_people = []
initial_infected = infect_random(people)
infected_people.append(initial_infected)
print(infected_people)
counted_infections = 0

我的目标是每个 infected_person(= 红点)都会感染所有靠近他的人。现在只有最初的感染者会感染其他人。所以我想如果我将每个被感染的人都添加到 infected_people 的列表中,那么它就会起作用。但是,添加行 infected_people.append(person) 时出现错误。

i = 0
while i < 30: #number of steps (time)
    for person in people: 
        random_walk(30, 400)
        i += 1
        for infected_person in infected_people: 
            if person.distance(infected_person) < 30: 
                person.color("red")
                infected_people.append(person)



turtle.done()
wn.exitonclick()

这是我收到的错误:

runfile('C:/Users/Noa Hoogeweg/Documents/BMT/PvL/Virus/Noa_Virus_goed.py', wdir='C:/Users/Noa Hoogeweg/Documents/BMT/PvL/Virus')
[<turtle.Turtle object at 0x000001FF4D3D9908>]
Traceback (most recent call last):

  File "C:\Users\Noa Hoogeweg\Documents\BMT\PvL\Virus\Noa_Virus_goed.py", line 78, in <module>
    person.color("red")

  File "C:\Users\Noa Hoogeweg\anaconda3\lib\turtle.py", line 2216, in color
    pcolor = self._colorstr(pcolor)

  File "C:\Users\Noa Hoogeweg\anaconda3\lib\turtle.py", line 2696, in _colorstr
    return self.screen._colorstr(args)

  File "C:\Users\Noa Hoogeweg\anaconda3\lib\turtle.py", line 1158, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))

TurtleGraphicsError: bad color string: red

我不知道你遇到了什么错误,但是 i + 1 行不会增加 i,要增加 i 的值你需要使用 i = i + 1i += 1 .

你对 person.color("red") 的调用看起来完全有效,我 运行 代码时没有收到错误。

根据错误的堆栈跟踪,乌龟只对颜色字符串做了两件事。首先,它测试它是否是 str —— 你的必须通过该测试才能得到你得到的错误。其次,它将颜色字符串传递给 tkinter 的 winfo_rgb() 方法,该方法 returns 一个 RGB 三元组。 Turtle 忽略三元组,它只是想看看该函数是成功还是抛出错误。如果它抛出错误,您会收到显示的消息:

TurtleGraphicsError: bad color string: red

所以球在 tkinter 的球场上,试试下面的小程序,看看 tkinter 是否在做正确的事情:

from tkinter import Button

# Button is an arbitrary widget choice
print(Button().winfo_rgb("red"))

如果有效,您应该会得到如下内容:

> python3 test.py
(65535, 0, 0)
>

在这种情况下,您的 turtle 代码与 tkinter 库连接的方式有些可疑。如果上面的操作失败,你应该得到类似的东西:

> python3 test.py
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print(Button().winfo_rgb("red"))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1156, in winfo_rgb
    self.tk.call('winfo', 'rgb', self._w, color))
_tkinter.TclError: unknown color name "red"
>

在这种情况下,您可能需要检查 tkinter 安装的有效性。

即使您解决了 "red" 问题,您的代码中还有其他错误会阻止它工作。下面是我的重写,以使其正确地达到 运行:

from turtle import Screen, Turtle
from random import randint, choice

def person_characteristics(people):
    for person in people:
        person.shape('circle')
        person.shapesize(0.2)
        person.speed('fastest')
        person.penup()
        x = randint(-200, 200)
        y = randint(-200, 200)
        person.setpos(x, y)
        person.showturtle()

def population(population_size):
    people = []

    for _ in range(population_size):
        people.append(Turtle(visible=False))

    return people

def random_walk(person, step_size, area_size):
    if -area_size < person.xcor() < area_size and -area_size < person.ycor() < area_size:
        person.right(randint(0, 360))
        person.forward(step_size)
    else:
        person.right(180)
        person.forward(step_size)

def infect_random(people):
    infected = choice(people)
    infected.color('red')
    return infected

screen = Screen()

people = population(50)
person_characteristics(people)

infected_people = []
initial_infected = infect_random(people)
infected_people.append(initial_infected)

counted_infections = 1

for _ in range(3000): # number of steps (time)
    for person in people:
        random_walk(person, 30, 400)

        for infected_person in infected_people:
            if person.pencolor() != 'red' and person.distance(infected_person) < 30:
                person.color('red')
                infected_people.append(person)
                break

screen.exitonclick()