python全局名称
我在python方面遇到了问题。我总是会遇到同样的错误:python全局名称,python,global-variables,Python,Global Variables,我在python方面遇到了问题。我总是会遇到同样的错误: Traceback (most recent call last): File "F:\test4", line 21, in <module> graph = dict([(label, node(label))] for label in node_labels) File "F:\test4", line 21, in <genexpr> graph = dict([(
Traceback (most recent call last):
File "F:\test4", line 21, in <module>
graph = dict([(label, node(label))] for label in node_labels)
File "F:\test4", line 21, in <genexpr>
graph = dict([(label, node(label))] for label in node_labels)
NameError: global name 'node' is not defined
回溯(最近一次呼叫最后一次):
文件“F:\test4”,第21行,在
graph=dict([(标签,节点(标签))]用于节点_标签中的标签)
文件“F:\test4”,第21行,在
graph=dict([(标签,节点(标签))]用于节点_标签中的标签)
NameError:未定义全局名称“节点”
#打开network.txt并填充节点并关闭文件
网络文件=打开(“network.txt”、“r”)
lines=[line.strip()表示网络_文件中的行]
网络_文件。关闭()
打印(len(行))
#将用network.txt中的信息填充的边缘
边=[]#三元组列表
node_labels=set()#节点标签集
graph={}#由标签键控的节点字典
对于行中的行:
strNode,strNeighbor,strMetric=line.split()[:3]
intMetric=int(标准)
追加((strNode、strNeighbor、intMetric))
node_labels.update([strNode,strNeighbor])
#创建图形
graph=dict([(标签,节点(标签))]用于节点_标签中的标签)
到这一行为止,我找不到全局变量节点有任何问题,它应该可以工作
谢谢 在您调用的最后一行
节点(标签)
。您在调用的最后一行节点(标签)
中定义了函数节点了吗?。您是否定义了函数节点
?为什么要定义它?
在您显示的代码中没有定义节点。。。也许你忘了导入?为什么要导入?
在您显示的代码中没有定义节点。。。可能您忘记了导入?您没有在包含的代码中的任何地方定义名为节点的变量或函数。它应该如何工作?节点标签是一组。图表是一本字典。为什么节点都需要?我假设是因为它从network.txt中获取一个数字并列出它:a=1 b=4您没有在包含的代码中的任何地方定义名为node
的变量或函数。它应该如何工作?节点标签是一组。图表是一本字典。为什么两个节点都需要?我假设是因为它从network.txt中获取一个数字并列出它:a=1 b=4
# open network.txt and populate nodes and close file
network_file = open("network.txt", "r")
lines = [line.strip() for line in network_file]
network_file.close()
print (len(lines))
# edges which will be populated with information in network.txt
edges = [] # list of <label, label, distance> triples
node_labels = set() # set of node labels
graph = {} # dictionary of nodes keyed by labels
for line in lines:
strNode, strNeighbor, strMetric = line.split()[:3]
intMetric = int(strMetric)
edges.append((strNode, strNeighbor, intMetric))
node_labels.update([strNode, strNeighbor])
# create graph
graph = dict([(label, node(label))] for label in node_labels)