簡體   English   中英

調用函數並在下一次運行中使用后如何存儲輸出

[英]How to store the output after calling a function and utilizing it in the next run

我在解釋器中運行了以下代碼,並稱為聯合函數

quick_find(10).union(3,4)

輸出: [0, 1, 2, 4, 4, 5, 6, 7, 8, 9]

quick_find(10).union(0,4)

輸出: [4, 1, 2, 3, 4, 5, 6, 7, 8, 9]

當我第二次調用union函數時,輸出列表應該是這個
[4, 1, 2, 4, 4, 5, 6, 7, 8, 9]

但是相反,它給了我[4, 1, 2, 3, 4, 5, 6, 7, 8, 9]作為輸出。 我如何獲得所需的輸出。 請建議

class quick_find:

    def __init__(self,n):
        self.id = [number for number in xrange(n)]


    def union(self,x,y):
        j = 0
        elements = self.id
        for i in elements:
            if i == elements[x]:
                elements[j] = elements[y]
            j = j+1

        self.id = elements
        return elements 

實際上,您實際上每次都在新實例上調用該union()方法:

您的代碼的改進版本:

class Quick_find:
    def __init__(self,n):
        self.id = range(n)    #just range() is enough

    def union(self,x,y):
        for i,elem in enumerate(self.id):    #use enumerate() for indexes
            if elem==x:
                self.id[i]=y

    def show(self):
        print self.id

q=Quick_find(10)       #create a instance
q.union(3,4)           #call union on that instance
q.union(0,4)           #call union on that instance
q.show()               

輸出:

[4, 1, 2, 4, 4, 5, 6, 7, 8, 9]

通過不將其分配給任何“占位符”對象/變量來創建所請求列表的新實例。 這樣,您的清單就可以保持完整。

myInstance = quick_find(10)
print(myInstance.union(0,4))
print(myInstance.union(3,4))

您現在實際要做的是;

myInstance = quick_find(10)
print(myInstance.union(0,4))

mySecondInstance = quick_find(10)
print(mySecondInstance.union(3,4))

..這顯然不能按照您想要的方式工作;)

暫無
暫無

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

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