所以,如果我有一个颜色列表:
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条线。
答案 0 :(得分: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
答案 1 :(得分:-1)
第一种方式: 你可以创建一个数组列表并插入&删除分配的颜色,然后当你想要计算数字的红色字段时,
第二种方式: 使用和插入在数组键中使用的颜色创建数组列表(键,值)并将每种颜色的计数放入值colors[
red=>0,
blue=>0,
green=>0
]
我希望有帮助。