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

时间:2013-03-31 01:39: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)):但是,即使将更多项目添加到列表中,范围也会保持不变。

3 个答案:

答案 0 :(得分:9)

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

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

for循环为列表创建一个迭代器,一次。一旦创建,迭代器就不知道你在循环中改变了列表。此处显示的while变体每次重新计算长度。

答案 1 :(得分:5)

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

{{1}}

答案 2 :(得分:1)

在行中:

for p in srcPts[1:]:  # skip the first item.

切片生成scrPtrs的新副本,因此它是固定大小。

免责声明:修改迭代器列表是错误的,但这有效......

在列表上创建一个迭代器可以防止复制并仍允许添加和插入项目:

L = [1,2,2,3,4,5,2,2,6]
it = iter(L)
next(it) # skip the first item
for i,p in enumerate(it,1):
    if p == 2:
        L.insert(i+1,7) # insert a 7 as the next item after each 2
    print(p)

输出:

2
7
2
7
3
4
5
2
7
2
7
6
相关问题