python - 我的函数内的列表对象保留与先前调用相同的值
问题描述
顺便说一句,这是我在 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]))
任何帮助,将不胜感激。谢谢!
解决方案
推荐阅读
- java - 如何更改 TestNG 报告中的异常消息
- java - 如何检查一个数字的每个数字是否大于或等于另一个数字?
- javascript - 如何禁用默认视频控件并显示自定义搜索栏
- c# - 仅删除列表中的第一个字符
- blockchain - 如何确保每个人都有正确有效的块状
- c# - 使用 Math.Round 函数在 C# 中的 Excel 工作表中将输入的数字转换为只有 2 个小数
- mysql - MySQL 显示第 n 个日期
- php - 如何使用 postman 为 web 服务设置 .php 文件的 url 和参数?
- bootstrap-4 - 为什么主容器在 nav 后面?
- entity-framework - 可以根据实体框架中的类型列将表拆分为多个实体吗?