Python:复制两个依赖列表及其依赖项

2024-03-29 13:19:16 发布

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

我被困在一个问题,我想这不是很难,但我找不到任何答案。你知道吗

我有两个对象列表,每一个都包含另一个对象的列表。我想复制它们来做测试和评估结果,然后再重复这个过程。最后,我会保持最好的成绩。你知道吗

但是,复制每个列表时,结果不是两个依赖列表,而是两个不再交互的列表,这并不奇怪。我怎样才能解决这个问题?有什么合适的方法吗?你知道吗

给定两类定义如下。你知道吗

import copy

class event:

    def __init__(self, name):
        self.name = name
        self.list_of_persons = []

    def invite_someone(self, person):
        self.list_of_persons.append(person)
        person.list_of_events.append(self)

class person:

    def __init__(self, name):
        self.name = name
        self.list_of_events = []

我试着写一些我所面临的情况的简单例子。print函数显示两个列表中的对象标识符不同。你知道吗

# Create lists of the events and the persons
the_events = [event("a"), event("b")]
the_persons = [person("x"), person("y"), person("z")]

# Add some persons at the events

the_events[0].invite_someone(the_persons[0])
the_events[0].invite_someone(the_persons[1])

the_events[1].invite_someone(the_persons[1])
the_events[1].invite_someone(the_persons[2])


print("Original :", id(the_persons[1]), id(the_events[0].list_of_persons[1]), id(the_events[1].list_of_persons[0]))


# Save the original configuration
original_of_the_events = copy.deepcopy(the_events)
original_of_the_persons = copy.deepcopy(the_persons)

for i in range(10):

    # QUESTION: How to make the following copies?
    the_events = copy.deepcopy(original_of_the_events)
    the_persons = copy.deepcopy(original_of_the_persons)

    print("   i =", i, ":", id(the_persons[1]), id(the_events[0].list_of_persons[1]), id(the_events[1].list_of_persons[0]))

    # Do some random stuff with the two lists
    # Rate the resulting lists
    # Record the best configuration

# Save the best result in a file

我考虑过使用一些字典并使列表独立,但这意味着我想避免大量的代码修订。你知道吗

提前感谢您的帮助!我对Python和StackExchange都是新手。你知道吗


Tags: ofthenameselfid列表eventsinvite
1条回答
网友
1楼 · 发布于 2024-03-29 13:19:16

由于deepcopy复制被复制对象的所有底层对象,因此对deepcopy执行两个独立的调用会断开对象之间的链接。如果您创建一个新对象,其中引用了这两个对象(如dict)并复制了该对象,那么将保留对象引用。你知道吗

workspace = {'the_persons': the_persons, 'the_events': the_events}
cpw = copy.deepcopy(workspace)

相关问题 更多 >