1

所以如果我有一个颜色列表:

colors = ['red', 'blue', 'green']

我用它们随机给线条上色。有没有可能计算一共有多少条红线?我知道如果每条线都有固定的颜色会更容易计算,但如果没有,我将如何计算呢?

colors = ['red', 'blue', 'green']
def lines(xcoord, ycoord):
    import random
    global colors
    penup()  
    goto(xcoord, ycoord)  
    pensize(3)  
    pendown()  
    color(random.choice(colors))  
    forward(100)  
    right(randint(0,360))
    penup()
for _ in range(3):
    lines(randint(min_xcoord, max_xcoord), \
        randint(min_ycoord, max_ycoord))

所以我想在绘制完成后找出总共有多少条红线,比如说3条线。

4

2 回答 2

1

假设您正在使用类似于此的代码:

from turtle import *
from random import choice
accuracy=64
colors = ['red', 'blue', 'green']
dist=400/accuracy
turn=360/accuracy
color_times = dict(zip(colors, [0, 0, 0])) # {'red':0, 'blue':0', 'green':0}
for j in range(5):
    my_color = choice(colors)
    color(my_color)
    color_times[my_color] += 1
    down()
    for i in range(0,360,turn):
        fd(dist)
        left(turn)
    up()
    fd(25)
mainloop()
print '{}:{}\n {}:{}\n {}:{}'.format('red', color_times['red'], 'blue', color_times['blue', 'green', color_times['green'])

根据您的行代码:

更改color(random.choice(colors))为:

my_color = random.choice(colors)
color(my_color)
color_times[my_color] += 1 # you have to initialize color_times before the loop
于 2013-04-13T03:25:24.917 回答
-1

第一种方法:您可以创建一个数组列表并在其中插入和删除颜色,然后当您想计算时,只需计算数组的红色字段,

第二种方法:创建数组 list(key,value) 并插入您在数组键中使用的颜色,并将每种颜色的计数放入 value

colors[
        red=>0,
        blue=>0,
        green=>0
      ]

我希望这会有所帮助。

于 2013-04-13T03:13:53.897 回答