Python Deepcopy和手动复制产生不同的结果

时间:2019-04-17 14:34:26

标签: python python-3.x

我在程序中使用了Deepcopy。它可以很好地处理结果。但是,使用Deepcopy会使程序的性能真正降低。因此,我尝试通过创建对象本身来进行手动复制。当我比较性能时,它可以提供更好的性能,但是程序结果是不同的。

这是我用于深度复制的代码。

temp_location = deepcopy(self.locations)

这是我用创建对象的手动副本替换Deepcopy之后的代码。

temp_location = self.new_deepcopy(self.locations)

def new_deepcopy(self, locations):
    result = []
    for location in locations:
        result.append(Location(
           location.location_id,
           location.open_time,
           location.close_time,
           location.price,
           location.score,
           location.duration)
        )
    return result

self.locationsLocation的列表,而Location是我这样定义的对象。

class Location:
    def __init__(self, location_id, open_time, close_time, price, score, duration):
        self.location_id = location_id
        self.open_time = open_time
        self.close_time = close_time
        self.price = price
        self.score = score
        self.duration = duration
        self.waiting_time = 0
        self.visit_time = 0
        self.leave_time = 0

如何在不使用Deepcopy的情况下使用不同的引用制作精确的副本?为什么我创建的new_copy会给出不同的结果?

1 个答案:

答案 0 :(得分:1)

我认为您的“ new_deepcopy”显然没有深度复制变量。就我对python的理解(如果我弄错了,请纠正我),Python中的每个变量都是指向内存位置的指针。因此,您的new_deepcopy可能正在做的只是将此指针传递给对象,而不是实际值。这就是为什么您的代码看起来更快但返回错误结果的原因。如果您想提高代码的性能,则可能需要考虑使用cython

相关问题