x轴增加+ 100 有没有办法使用python 3
使用for循环缩短代码def peasInAPod():
win=GraphWin(100,500)
peas=eval(input("how many peas? "))
if peas == 5:
p=Circle(Point(50,100),50)
p2=Circle(Point(150,100),50)
p3=Circle(Point(250, 100),50)
p4=Circle(Point(350,100),50)
p5=Circle(Point(450,100),50)
p.draw(win)
p2.draw(win)
p3.draw(win)
p4.draw(win)
p5.draw(win)
答案 0 :(得分:1)
我假设您正在寻找以下内容:
def peasInAPod():
win=GraphWin(100,500)
peas=eval(input("how many peas? "))
list_of_peas = [Circle(Point(50 + i * 100, 100),50) for i in range(0,peas)]
for p in list_of_peas:
p.draw(win)
编辑列表理解也可以更改为:
list_of_peas = [Circle(Point(i, 100),50) for i in range(50,peas*100,100)]
答案 1 :(得分:0)
是的,使用列表理解:
def peasInAPod():
win=GraphWin(100,500)
peas=eval(input("how many peas? "))
if peas == 5:
[Circle(Point(i, 100), 50).draw(win)
for i in range(50, 550, 100)]
答案 2 :(得分:0)
修改强>
你要求最短的,对吧?
def peasInAPod():
win = GraphWin(100,500)
list(map(lambda p: p.draw(win), [Circle(Point((i*100)+50,100),50) for i in range(int(input('How many peas? ')))]))
您需要list
才能真正执行lambda
。
原始回答:
这样的东西?
def peasInAPod():
win = GraphWin(100,500)
peas = eval(input('How many peas? ')) # Use something safer than eval
for i in range(peas):
p = Circle(Point((i*100)+50,100),50)
p.draw(win)
我假设您不需要在其他地方重用p*
变量,并且您不需要稍后存储或引用豌豆列表(这只是绘制它们)。你提供的规格越多,你得到的答案就越好!希望这会有所帮助。
只是为了好玩,这里也是一个发电机!对不起,我忍不住了......
def the_pod(how_many):
for p in range(how_many):
yield Circle(Point((p*100)+50,100),50)
def peasInAPod():
win = GraphWin(100,500)
of_all_the_peas = input('How many peas? ') # raw_input for Python < 3
for one_of_the_peas in the_pod(int(of_all_the_peas)):
one_of_the_peas.draw(win)
此复制,粘贴和执行没有任何依赖关系。万一你是在追求一个无限的发电机,迫使人们拥有无限豌豆。
def the_pod():
p = 0
while True:
yield (p*100)+50
p += 1
def peasInAPod():
print('You may have all the peas. Well. Only their x-coordinate.')
for one_of_the_peas in the_pod():
print(one_of_the_peas)
peasInAPod()
我要去买一些豌豆汤了。谢谢!