Python的Deepcopy和Manual Copy给出了不同的结果

2024-05-04 09:17:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在我的程序中使用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会给出不同的结果


Tags: self程序idnewclosetimelocationopen
1条回答
网友
1楼 · 发布于 2024-05-04 09:17:52

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

相关问题 更多 >