【问题标题】:How can I use a for loop to make my code look less repetitive here?如何使用 for 循环使我的代码在这里看起来不那么重复?
【发布时间】:2017-12-04 14:24:19
【问题描述】:

我的意思是使用 python 中的 graphics.py 在图形窗口上画线。 我这里的代码非常重复,我需要把它变成一个我不知道该怎么做的 for 循环。

win=GraphWin("Patch1", 100, 100)
win.setBackground("white")
l1=Line(Point(0,80),Point(20,100))
l1.setFill("red")
l1.draw(win)
l2=Line(Point(0,60),Point(40,100))
l2.setFill("red")
l2.draw(win)
l3=Line(Point(0,40),Point(60,100))
l3.setFill("red")
l3.draw(win)
l4=Line(Point(0,20),Point(80,100))
l4.setFill("red")
l4.draw(win)
l5=Line(Point(0,0),Point(100,100))
l5.setFill("red")
l5.draw(win)

【问题讨论】:

  • 这需要一个函数。
  • 你试过了吗? Point(0,80-i*20),Point(20+i*20,100) 作为提示
  • 试试for 循环。
  • 为什么不用函数?

标签: python for-loop


【解决方案1】:

至少:

for p1, p2 in [(Point(0,80), Point(20,100)), (Point(0,60), Point(40,100), ...]:
    l = Line(p1, p2)
    l.setFill("red")
    l.draw(win)

唯一不同的是用于生成线的确切点;其余的可以抽象成循环体,如图所示。

我把它作为一个练习来弄清楚如何不那么明确地生成Points 的列表。

【讨论】:

    【解决方案2】:

    这应该可行:

    win = GraphWin("Patch1", 100, 100)
    win.setBackground("white")
    for i in range(20,101,20):
        l = Line(Point(0,100-i),Point(i,100))
        l.setFill("red")
        l.draw(win)
    

    您也可以在此处使用函数。我会把它留给你。

    【讨论】:

    • 如何使用相同的方法在图形窗口上创建十字交叉设计?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    相关资源
    最近更新 更多