如何在调用函数后存储输出并在下次运行时使用它



我在解释器中运行了下面的代码并调用了联合函数

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]

当我第二次调用联合函数时,输出列表应该是这样的
[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))

. .这显然不是你想要的方式;)

最新更新