【问题标题】:for loop to shorten codefor循环缩短代码
【发布时间】:2016-11-05 23:12:09
【问题描述】:

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)

【问题讨论】:

标签: python-3.x for-loop


【解决方案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)

EDIT列表推导也可以改为:

list_of_peas = [Circle(Point(i, 100),50) for i in range(50,peas*100,100)]

【讨论】:

  • 您可以得到正确的i 并在适当的范围内避免额外的算术步骤
  • @Copperfield 是的,谢谢。在编辑中将其添加为替代版本
【解决方案2】:

编辑

你要的是最短的,对吧?

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()

我要去喝点豌豆汤。谢谢!

【讨论】:

    【解决方案3】:

    是的,通过使用列表推导:

    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)]
    

    【讨论】:

    • 为什么要在这里使用列表推导?你不是想建立一个列表。
    • 它不比直接做for i in range(stuff): Circle(other_stuff).draw(win)短,而且它无缘无故地构建和丢弃一个中间列表。
    • 您不应该使用函数式构造,即列表推导式来获得副作用。只需使用 for 循环。
    猜你喜欢
    • 2019-02-27
    • 2011-12-23
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多