Python 3.x for循环以缩短代码
x轴增加+100 有没有办法使用python 3缩短for循环的代码Python 3.x for循环以缩短代码,python-3.x,for-loop,Python 3.x,For Loop,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)
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)
我假设您正在寻找以下内容:
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)]
是的,通过使用列表理解:
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)]
编辑
你要的是最短的,对吗
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? ')))]))
您需要列表
来实际执行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*
变量,也不需要在以后存储或引用PEA列表(这只是绘制它们)。你提供的规格越多,你得到的答案就越好!希望这有帮助
只是为了好玩,这里还有一个发电机!对不起,我没办法
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)
我要去买些豌豆汤。谢谢 为什么要在这里使用列表?你不是在试图建立一个列表。它并不比仅仅为范围内的i(stuff)做
:圈(other_stuff)。直接绘制(win)
,它会毫无理由地建立并丢弃一个中间列表。你不应该为了副作用而使用函数结构,即列表理解。只需使用一个for-loop,就可以得到正确的i
,并在适当的范围内避免额外的运算step@Copperfield是的,谢谢。在editnever use eval:,,中将其添加为替代版本。在这种情况下,使用int(输入(…)
将是非常棒的,如果您能指出以下任何答案(当然不一定是我的答案)是否解决了您的问题:)
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()