【问题标题】:Python: Copy two dependent lists together with their dependencePython:复制两个依赖列表及其依赖关系
【发布时间】:2015-06-26 04:20:57
【问题描述】:

我遇到了一些我认为不是很困难的问题,但我找不到任何答案。

我有两个对象列表,每个对象都包含另一个对象列表。我想复制它们以在重复该过程之前进行测试并评估结果。最后,我会保持最好的结果。

但是,当复制每个列表时,不出所料,结果不是两个依赖列表,而是两个不再交互的列表。我该如何解决这个问题?有什么合适的方法吗?

给定两个类定义如下。

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 = []

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

# 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 的新手。

【问题讨论】:

  • 我发现您的要求相当不清楚。 “从属”和“从属”列表是什么意思?您能否提供一些示例,说明每个列表的内容以及处理后相应的预期内容?
  • 对不起。我的意思是,在复制之后,修改event 类中的person 不会导致对the_persons 列表中对应的person 的任何修改。我希望他们仍然联系在一起。如果执行代码,你会得到类似:Original : 49619744 49619744 49619744 而在循环中,你会得到:i = 0 : 52093840 52093448 52093448 所以对象是相同的(id 是不同的)。这就是我所说的依赖。我希望这能澄清我的问题。

标签: python python-3.x copy dependencies python-3.4


【解决方案1】:

由于 deepcopy 会复制所复制事物的所有底层对象,因此对 deepcopy 执行两次独立调用会破坏对象之间的链接。如果你创建一个引用这两个东西的新对象(如字典)并复制该对象,这将保留对象引用。

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

【讨论】:

  • 非常感谢!这救了我!我也尝试了一个元组,它也运行良好。我知道出了什么问题,但不知道如何复制对象:这做得很好。谢谢!
猜你喜欢
  • 2014-05-06
  • 1970-01-01
  • 2015-12-28
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
相关资源
最近更新 更多