首页 > 解决方案 > 我的函数内的列表对象保留与先前调用相同的值

问题描述

顺便说一句,这是我在 Stack Overflow 上的第一篇文章。

我创建了一个名为“Network”的类,它包含一个节点列表,其中包含一个字符串作为数据和一个属性列表以及表示该数据和相关程度的相应权重。即NetworkObject.data = "dog"NetworkObject.attributes = [("four_legs", 1.0), ("brown", 0.2)]。然后这些节点根据属性之间的平均相似度相互连接。这将创建一个图形结构,其中边存储在“节点”变量“已连接”中。

目标是创建函数“pulse”,它返回节点到调用“pulse”的节点一定距离(由“strength”参数确定)。

“网络”按我的意愿工作,“脉冲”功能在第一次通话时工作。但是每当我第二次调用它时,'traversal'(这是一个包含要返回的节点的变量)仍然包含上一次调用的所有值。因此,例如,如果我调用“脉冲”并且traversal = [1.0, .5, .75], the next time I call it, those same values remain in the list.

我尝试将“遍历”列表转移到第二个变量,并在返回之前用空列表替换“遍历”,但我仍然得到相同的结果。

节点类:

class Node:
    """Class of data containers with the dict variable 'attributes'. Using these attributes, the 'Network' structure forms connections between 
    collections of nodes. Note: Many of the 'Node' class functions parallel those of the 'Network' class. The node functions directly change the nodes
    according to the arguments in the function, while the network functions assess what should be changed and delegates those changes to the Node class"""
    def __init__(self, idx, data):
        self.data = data
        self.idx = idx
        self.attributes = {}
        self.connections = []

网络类

class Network:
    """Graph Structure which organizes 'Nodes' according to their attribute weight."""
    def __init__(self):
        self.nodeList = []

脉冲函数(网络类的函数):

    def pulse(self, node_idx, strength, weight=1, traversed=[]):
        """A pulse is the main 'search' function of the ACN. It recursively digs into the network in all directions 
        until it's strength reaches zero. At this point it returns all the traversed nodes. Note:
        strength is drained by the inverse of weight each node i.e. weight of .7 = .3 drained"""
        node = self.nodeList[node_idx]
        strength -= (1 - weight)
        if strength >= 0:
            traversed.append(node.idx)
            for conn_node in node.connections:
                if conn_node[0] not in traversed:
                    traversed = self.pulse(conn_node[0], strength, conn_node[1], traversed)
            
        return traversed

控制台功能,允许用户为脉冲呼叫提供必要的信息:

   def pulse(self):
        print("Network Nodes(idx, data): ", end="")
        print([(node.idx, node.data) for node in self.network.nodeList])
        node = int(input("What is the index of the node you'd like to pulse?"))
        strength = float(input("Strength?: "))
        traversal = self.network.pulse(node, strength)
        print("Returns: {}".format([self.network.nodeList[idx].data for idx in traversal]))

任何帮助,将不胜感激。谢谢!

标签: pythonlistvariablesnetworking

解决方案


推荐阅读