簡體   English   中英

Python,避免覆蓋函數的參數

[英]Python, Avoid overwriting argument to function

我是Python的新手,很驚訝地發現我的代碼的這一部分:

print len(allCommunities[5].boundary)
allCommunities[5].surface = triangularize(allCommunities[5].boundary)
print len(allCommunities[5].boundary)

輸出此:

1310
2

下面是我在Processing(像Java這樣的語言)中編寫並移植到Python中的函數。 它做了它應該做的(三角形多邊形),但我的目的是傳遞inBoundary以使用函數但不刪除所有allCommunities[5].boundary中的元素。

我該如何防止所有allCommunities[5].boundary在函數中被修改? 附帶說明一下,如果我在函數中做其他一些愚蠢的事情,但仍然習慣於Python,我將不勝感激。

def triangularize(inBoundary):
    outSurface = []

    index = 0;
    while len(inBoundary) > 2:
        pIndex = (index+len(inBoundary)-1)%len(inBoundary);
        nIndex = (index+1)%len(inBoundary);

        bp = inBoundary[pIndex]
        bi = inBoundary[index]
        bn = inBoundary[nIndex]

        # This assumes the polygon is in clockwise order
        theta = math.atan2(bi.y-bn.y, bi.x-bn.x)-math.atan2(bi.y-bp.y, bi.x-bp.x);
        if theta < 0.0: theta += math.pi*2.0;

        # If bp, bi, and bn describe an "ear" of the polygon
        if theta < math.pi:
            inside = False;

            # Make sure other vertices are not inside the "ear"
            for i in range(len(inBoundary)):
                if i == pIndex or i == index or i == nIndex: continue;

                # Black magic point in triangle expressions
                # http://answers.yahoo.com/question/index?qid=20111103091813AA1jksL
                pi = inBoundary[i]
                ep = (bi.x-bp.x)*(pi.y-bp.y)-(bi.y-bp.y)*(pi.x-bp.x)
                ei = (bn.x-bi.x)*(pi.y-bi.y)-(bn.y-bi.y)*(pi.x-bi.x)
                en = (bp.x-bn.x)*(pi.y-bn.y)-(bp.y-bn.y)*(pi.x-bn.x)

                # This only tests if the point is inside the triangle (no edge / vertex test)
                if (ep < 0 and ei < 0 and en < 0) or (ep > 0 and ei > 0 and en > 0):
                    inside = True;
                    break

            # No vertices in the "ear", add a triangle and remove bi
            if not inside:
                outSurface.append(Triangle(bp, bi, bn))
                inBoundary.pop(index)
        index = (index+1)%len(inBoundary)
    return outSurface

print len(allCommunities[5].boundary)
allCommunities[5].surface = triangularize(allCommunities[5].boundary)
print len(allCommunities[5].boundary)

Python中的列表是可變的,以及諸如的操作

inBoundary.pop

修改它們。 簡單的解決方案是復制函數內的列表:

def triangularize(inBoundary):
    inBoundary = list(inBoundary)
    # proceed as before

最簡單的方法是復制傳入的參數:

def triangularize(origBoundary):
    inBoundary = origBoundary[:]

然后你的其余代碼可以保持不變。

暫無
暫無

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

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