我对Python语言相对较新,并且想知道是否有更有效的方法来声明多个变量。我为了制作随机放置的颜色三角形而宣布了很多随机数。
from time import sleep
from graphics import *
from random import randint
def main():
win = GraphWin("Wow!", 500, 500)
win.setBackground("black")
for i in range(1,100):
rand = randint(0,500)
rand1 = randint(0,500)
rand2 = randint(0,500)
rand3 = randint(0,500)
rand4 = randint(0,500)
rand5 = randint(0,500)
randR = randint(0,255)
randG = randint(0,255)
randB = randint(0,255)
p = Polygon(Point(rand,rand1), Point(rand2,rand3), Point(rand4,rand5)).draw(win)
p.setFill(color_rgb(randR, randG, randB))
Circle(Point(100,100), i).draw(win).setFill('blue')
if i > 60:
Circle(Point(200,400), (i-50)).draw(win).setFill('red')
if i > 30:
Circle(Point(400,130), (i-30)).draw(win).setFill('green')
time.sleep(.03)
win.getMouse()
win.close()
main()
有问题的变量都是随机数变量(rand)。
我也有兴趣知道如何在其他语言中完成此操作,或者是否存在跨语言的常用方法。
答案 0 :(得分:1)
使用列表:
rand_nums = [randint(0, 500) for i in range(6)] # 6 random numbers
rand_rgb = [randint(0, 255) for i in range(3)] # 3 random rgb-range numbers
p = Polygon(Point(rand_nums[0], rand_nums[1]), Point(rand_nums[2], rand_nums[3]), Point(rand_nums[4], rand_nums[5])).draw(win)
...
等等。