如何使用for循环添加参数元素?

2024-06-01 03:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

使用cs1graphics模块,我制作了一个包含4个点对象的列表。我想用列表对象中的点绘制一个多边形,每次迭代(在for循环中)都要将列表中的一个元素添加到Polygon参数。列表中的点对象需要以多边形的形式堆叠在彼此的顶部,以便绘制出整个对象。实际上,列表中某个位置的点对象将覆盖上一次迭代中的上一个对象。最后,我“画”了一个点(即列表中的最后一点)。我该怎么解决这个问题?你知道吗

编辑:我试过使用.append,但这会把所有参数变成一个列表对象,显然我不能绘制列表。你知道吗

self._list = [Point(200,200),Point(400,200),Point(400,400),Point(200,400),Point(200,200)]
    for i in range(4):
        self._poly = Polygon(self._list[i],)

Tags: 模块对象self元素编辑列表for参数
3条回答

只需传入列表本身,如下所示:

self._list = [Point(200,200),Point(400,200),Point(400,400),Point(200,400)]
self._poly = Polygon(self._list)

请注意,您don't need the last point

The last point is automatically connected back to the first to close the polygon.

我想你想要的是:

self._poly = Polygon(*self._list)

*将列表解压为参数,并将这些参数作为单独的参数传递给函数。你知道吗

你也可以直接把点列表传进去。你知道吗

self._poly = Polygon(self._list)

它也会起作用的。你知道吗

两者

self._list = [Point(200,200),Point(400,200),Point(400,400),Point(200,400),Point(200,200)]
self._poly = Polygon(self._list)

以及

self._list = [Point(200,200),Point(400,200),Point(400,400),Point(200,400),Point(200,200)]
self._poly = Polygon(*self._list)

会有用的。不需要循环。你知道吗

你知道吗

如果坚持以增量方式在循环中构建多边形,可以执行以下操作:

self._list = [Point(200,200),Point(400,200),Point(400,400),Point(200,400),Point(200,200)]
self._poly = Polygon()
for point in self._list:
    self._poly.addPoint(point)

相关问题 更多 >