如何创建具有动态范围的for循环?

2024-06-11 18:41:16 发布

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

我正在遍历一个列表。元素可以在迭代期间添加到此列表中。所以问题是循环只遍历这个列表的原始长度。

我的代码:

    i = 1
    for p in srcPts[1:]:  # skip the first item.
        pt1 = srcPts[i - 1]["Point"]
        pt2 = p["Point"]

        d = MathUtils.distance(pt1, pt2)
        if (D + d) >= I:
            qx = pt1.X + ((I - D) / d) * (pt2.X - pt1.X)
            qy = pt1.Y + ((I - D) / d) * (pt2.Y - pt1.Y)
            q  = Point(float(qx), float(qy))
            # append new point q.
            dstPts.append(q)
            # Insert 'q' at position i in points s.t. 'q' will be the next i.
            srcPts.insert(i, {"Point": q})
            D = 0.0
        else:
            D += d
        i += 1

我试过使用for i in range(1, len(srcPts)):,但再次尝试,即使列表中添加了更多项,范围仍然保持不变。


Tags: the代码in元素列表forfloatpoint
2条回答

在这种情况下,您需要使用while循环:

i = 1
while i < len(srcPts):
    # ...
    i += 1

循环为您的列表创建一个迭代器,once。一旦创建了迭代器,它就不知道您更改了循环中的列表。这里显示的while变量每次都会重新计算长度。

问题是,当您将len(srcPts)作为参数传递给range生成器时,只计算一次len(srcPts)。因此,您需要有一个终止条件,在每次迭代期间重复计算当前长度srcPts。有很多方法可以做到这一点,例如:

while i < len(srcPts):


  ....

相关问题 更多 >