10

リストを繰り返し処理しています。反復中に要素をこのリストに追加できます。したがって、問題は、ループがこのリストの元の長さだけを反復することです。

私のコード:

    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)):ましたが、リストにアイテムを追加しても範囲は同じままです。

4

3 に答える 3

2

行で:

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
于 2013-03-31T01:53:55.497 に答える