【问题标题】:Trouble walking parallel lists in Python for loop在 Python for 循环中遍历并行列表时遇到问题
【发布时间】:2016-09-12 23:13:38
【问题描述】:

我正在尝试编写代码,在列表 coords 中相同索引处包含的 xy 坐标处绘制列表 sides 中由长宽对表示的每个矩形

变量 coords 包含大小为 2 的子列表,其中每个值代表一个 x 和一个 y 坐标。

变量边还包含大小为 2 的子列表,每个值代表矩形的长度和宽度。

我已经写了一个名为 draw_rectangle 的函数,它的参数是两个整数,分别代表矩形的长度和宽度。

话虽如此,现在我很困惑制作for 循环。 这是我想出来的,但似乎不起作用

for pair in sides:
    penup()
    goto(coords[index])
    pendown()
    draw_ractangle(sides[index][0], sides[index][1])

还是我必须去

for draw_ractangle()

有什么建议吗?谢谢

【问题讨论】:

  • 您拥有的当前代码现在会发生什么?
  • 那行不通,因为你还没有告诉 Python index 是什么。但是,有一个更好的方法:您可以使用内置的zip 函数并行循环coordssides,您可以在tutorial 中阅读。

标签: python for-loop turtle-graphics


【解决方案1】:

这似乎是enumerate() 和结构分配的问题:

sides = [(34, 23), (65, 72)]
coords = [(10, 100), (-45, 60)]

# ...

for index, (width, height) in enumerate(sides):
    penup()
    goto(coords[index])
    pendown()
    draw_rectangle(width, height)

【讨论】:

    【解决方案2】:

    我希望看到这个用 zip 处理:

    for (location, dimensions) in zip(coords, sides):
      penup()
      goto(location)
      pendown()
      draw_rectangle(*dimensions)
    

    一般来说,python 风格更倾向于避免循环遍历索引,而倾向于循环遍历内容。 zip 函数是实现此目的的好方法,它通过创建一个元组列表。 我对并行列表模式感到担忧,它通常很脆弱并且容易损坏,并且希望看到代表每个要绘制的对象的数据结构,以避免位置和维度不同步的危险。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      相关资源
      最近更新 更多