removing an instance of an object in python list

前端 未结 3 739
北恋
北恋 2020-12-11 01:13

I Think this should work but its giving me an error. I have a list that contains objects of class node. I have two different lists

  1. open_list
3条回答
  •  误落风尘
    2020-12-11 01:53

    If I read the question right, python's default of comparing the memory locations is the behavior he is looking for, but is not getting. Here's a working example where a custom class is defined Node, it show's that there is no need for the __eq__(self, other).

    class Node(object):
        pass
    
    open_node_list = []
    node_list = []
    
    for i in range(10):
        a_node = Node()
        open_node_list.append(a_node)
        node_list.append(a_node)
    
    removed = open_node_list.pop()
    node_list.remove(removed)
    

    I can't be sure, because you did not show where your open_node_list and node_list were defined, but I suspect that the lists themselves reference the same list object. If that's the case, the popping from open_node_list also pops from node_list, therefore the node will no longer exist when you call remove. Here is example in which node_list and open_node_list are really the same list and so changes to one affect the other:

    class Node(object):
      pass
    
    open_node_list = []
    node_list = open_node_list # <-- This is a reference, not a copy.
    
    open_node_list.append(Node())
    print(node_list)
    

    One way you can copy a list is:

    node_list = open_node_list[:]
    

提交回复
热议问题