簡體   English   中英

如何創建具有動態范圍的for循環?

[英]How do you create a for loop with a dynamic range?

我正在遍歷列表。 可以在迭代期間將元素添加到此列表中。 所以問題是循環只迭代這個列表的原始長度。

我的代碼:

    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)):使用for i in range(1, len(srcPts)):但是,即使將更多項目添加到列表中,范圍也會保持不變。

在這種情況下,您需要使用while循環:

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

for循環為列表創建一個迭代器, 一次 一旦創建,迭代器就不知道你在循環中改變了列表。 此處顯示的while變量每次都會重新計算長度。

問題是當你將它作為參數傳遞給range生成器時, len(srcPts)只計算一次。 因此,您需要有一個終止條件,在每次迭代期間重復計算srcPts的當前長度。 有很多方法可以做到這一點,例如:

while i < len(srcPts):


  ....

在線:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM