我正在努力研究如何从函数中传递参数,以便我可以在另一个函数中填充列表 - 我的代码是:
infinity = 1000000
invalid_node = -1
startNode = 0
#Values to assign to each node
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
#read in all network nodes
def network():
f = open ('network.txt', 'r')
theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
print theNetwork
return theNetwork
#for each node assign default values
def populateNodeTable():
nodeTable = []
index = 0
f = open('network.txt', 'r')
for line in f:
node = map(int, line.split(','))
nodeTable.append(Node())
print "The previous node is " ,nodeTable[index].previous
print "The distance from source is " ,nodeTable[index].distFromSource
index +=1
nodeTable[startNode].distFromSource = 0
return nodeTable
#find the nearest neighbour to a particular node
def nearestNeighbour(currentNode, theNetwork):
nearestNeighbour = []
nodeIndex = 0
for node in nodeTable:
if node != 0 and currentNode.visited == false:
nearestNeighbour.append(nodeIndex)
nodeIndex +=1
return nearestNeighbour
currentNode = startNode
if __name__ == "__main__":
nodeTable = populateNodeTable()
theNetwork = network()
nearestNeighbour(currentNode, theNetwork)
所以,我试图在最近的邻居函数中填充最近的邻居列表,其中包含最接近其他节点的节点列表。现在,所有其他函数都正常工作,所有参数传递都应该正常运行。 但是,my nearestNeighbour函数会抛出此错误消息:
如果节点!= 0和 theNetwork [currentNode] .visited == false:AttributeError:'list'对象 没有'已访问'属性
(对于布局抱歉,还没有完全理解代码引用的使用)
答案 0 :(得分:1)
那是因为theNetwork[currentNode]
返回一个列表。换句话说:theNetwork
是一个列表列表。
这是完成它的路线:
theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
答案 1 :(得分:1)
class Node(object):
def __init__(self, me, dists):
super(Node,self).__init__()
self.me = me
self.dists = dists
_inf = Network.INF
self.neighbors = sorted((i for i,dist in enumerate(self.dists) if i!=me and dist!=_inf), key=dists.__getitem__)
self.clear()
def clear(self):
self.dist = None
self.prev = None
def nearestNeighbor(self):
try:
return self.neighbors[0]
except IndexError:
return None
def __str__(self):
return "{0}: {1}".format(self.me, self.dists)
class Network(object):
INF = 10**6
@classmethod
def fromFile(cls, fname, delim=None):
with open(fname) as inf:
return cls([[int(dist) for dist in line.split(delim)] for line in inf])
def __init__(self, distArray):
super(Network,self).__init__()
self.nodes = [Node(me,dists) for me,dists in enumerate(distArray)]
def __str__(self):
return '\n'.join(self.nodes)
def floodFill(self, fromNode):
_nodes = self.nodes
for n in _nodes:
n.clear()
_nodes[fromNode].dist = 0
# left as an exercise ;-)
def distances(self):
return [n.dist for n in self.nodes]
def main():
nw = Network.fromFile('network.txt', delim=',')
print(nw)
nw.floodFill(fromNode=0)
print(nw.distances())
if __name__=="__main__":
main()
答案 2 :(得分:0)
theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
theNetwork
是一个列表清单。列表(theNetwork[currentNode]
)没有visited
属性。
也许你想要的东西是:
for line in f.readlines():
theNetwork.extend((int(node) for node in line.split(',')))