Python 地图函数

发布于 2024-10-22 00:47:36 字数 3696 浏览 2 评论 0原文

我需要一些有关 Python 地图功能的帮助。我正在尝试执行此代码,但出现错误:

更新的帖子

这是我的确切代码,以及每个函数的输出:

infinity = 1000000
invalid_node = -1
startNode = 0

#Values to assign to each node
class Node:
     def __init__(self):
       self.distFromSource = infinity
       self.previous = invalid_node
       self.visited = False

#read in all network nodes
#node = the distance values between nodes
def network():
    f = open ('network.txt', 'r')
    theNetwork = [[int(networkNode) for networkNode in line.split(',')] for line in f.readlines()]
    #theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
    print theNetwork

    return theNetwork

#for each node assign default values
#populate table with default values
def populateNodeTable(): 
    nodeTable = []
    index = 0
    f = open('network.txt', 'r')
    for line in f: 
      networkNode = map(int, line.split(',')) 
      nodeTable.append(Node())

      print "The previous node is " ,nodeTable[index].previous 
      print "The distance from source is " ,nodeTable[index].distFromSource
      #print networkNode
      index +=1
    nodeTable[startNode].distFromSource = 0 

    return nodeTable

currentNode = startNode

#find the nearest neighbour to a particular node
def nearestNeighbour(currentNode, theNetwork):
     listOfNeighbours = []
     nodeIndex = 0
     for networkNode in theNetwork[currentNode]:
          if networkNode != 0 and nodeTable[nodeIndex].visited == False:
            listOfNeighbours.append(networkNode)
            nodeIndex +=1
     print "The nearest neighbours are", listOfNeighbours
##     #print node.distFromSource, node.previous, node.visited
##
     return listOfNeighbours

def tentativeDistance (theNetwork, listOfNeighbours):
    shortestPath = []
    for nodeIndex in theNetwork:
         currentDistance = listOfNeighbours[nodeIndex] + startNode
         print currentDistance
         if currentDistance[theNetwork][nodeIndex] < Node.distFromSource:
            theNetwork[node].previous = nodeIndex
            theNetwork[node].distFromSource = nodeIndex
            theNetwork[node].visited = True;
            shortestPath.append(indexNode)
            nodeIndex +=1
    print shortestPath

if __name__ == "__main__":
     nodeTable = populateNodeTable()
    #nodeTable = populateNodeTable(self)
     theNetwork = network()
     #listOfNeighbours = nearestNeighbour(currentNode, theNetwork)
     #tentativeDistance(theNetwork, listOfNeighbours)

我的网络函数的输出是一个 2D 列表:

[[0, 2, 4, 1, 6, 0, 0], [2, 0, 0, 0, 5, 0, 0], [4, 0, 0, 0, 5, 5, 0], [1, 0, 0, 0, 1, 1, 0], [6, 5, 0, 1, 0, 5, 5], [0, 0, 5, 1, 5, 0, 0], [0, 0, 0, 0, 5, 0, 0]]

输出我的 populateNodeTable 函数是:

The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000

我的网络文本文件具有以下格式(减去行间距):

0,2,4,1,6,0,0

2,0,0,0,5,0,0

4,0, 0,0,5,5,0

1,0,0,0,1,1,0

6,5,0,1,0,5,5

0,0,5,1,5,0,0

0, 0,0,0,5,0,0

错误是:

currentDistance = listOfNeighbours[nodeIndex] + startNode
TypeError: list indices must be integers, not list

这是我的 listOfNeighbours 的内容,在我的另一个函数中生成:

[2, 4, 1, 6]

我不明白这方面的 Python 文档,这听起来并不容易初学者

I need some help with Python's map function. I am trying to execute this code, though I get an error:

Updated Post

This is my exact code, along with the outputs of each function:

infinity = 1000000
invalid_node = -1
startNode = 0

#Values to assign to each node
class Node:
     def __init__(self):
       self.distFromSource = infinity
       self.previous = invalid_node
       self.visited = False

#read in all network nodes
#node = the distance values between nodes
def network():
    f = open ('network.txt', 'r')
    theNetwork = [[int(networkNode) for networkNode in line.split(',')] for line in f.readlines()]
    #theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
    print theNetwork

    return theNetwork

#for each node assign default values
#populate table with default values
def populateNodeTable(): 
    nodeTable = []
    index = 0
    f = open('network.txt', 'r')
    for line in f: 
      networkNode = map(int, line.split(',')) 
      nodeTable.append(Node())

      print "The previous node is " ,nodeTable[index].previous 
      print "The distance from source is " ,nodeTable[index].distFromSource
      #print networkNode
      index +=1
    nodeTable[startNode].distFromSource = 0 

    return nodeTable

currentNode = startNode

#find the nearest neighbour to a particular node
def nearestNeighbour(currentNode, theNetwork):
     listOfNeighbours = []
     nodeIndex = 0
     for networkNode in theNetwork[currentNode]:
          if networkNode != 0 and nodeTable[nodeIndex].visited == False:
            listOfNeighbours.append(networkNode)
            nodeIndex +=1
     print "The nearest neighbours are", listOfNeighbours
##     #print node.distFromSource, node.previous, node.visited
##
     return listOfNeighbours

def tentativeDistance (theNetwork, listOfNeighbours):
    shortestPath = []
    for nodeIndex in theNetwork:
         currentDistance = listOfNeighbours[nodeIndex] + startNode
         print currentDistance
         if currentDistance[theNetwork][nodeIndex] < Node.distFromSource:
            theNetwork[node].previous = nodeIndex
            theNetwork[node].distFromSource = nodeIndex
            theNetwork[node].visited = True;
            shortestPath.append(indexNode)
            nodeIndex +=1
    print shortestPath

if __name__ == "__main__":
     nodeTable = populateNodeTable()
    #nodeTable = populateNodeTable(self)
     theNetwork = network()
     #listOfNeighbours = nearestNeighbour(currentNode, theNetwork)
     #tentativeDistance(theNetwork, listOfNeighbours)

The output of my network function is a 2D list:

[[0, 2, 4, 1, 6, 0, 0], [2, 0, 0, 0, 5, 0, 0], [4, 0, 0, 0, 5, 5, 0], [1, 0, 0, 0, 1, 1, 0], [6, 5, 0, 1, 0, 5, 5], [0, 0, 5, 1, 5, 0, 0], [0, 0, 0, 0, 5, 0, 0]]

The output of my populateNodeTable function is:

The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000
The previous node is  -1
The distance from source is  1000000

My network text file has this format (minus the line spacing):

0,2,4,1,6,0,0

2,0,0,0,5,0,0

4,0,0,0,5,5,0

1,0,0,0,1,1,0

6,5,0,1,0,5,5

0,0,5,1,5,0,0

0,0,0,0,5,0,0

The error is:

currentDistance = listOfNeighbours[nodeIndex] + startNode
TypeError: list indices must be integers, not list

This is the contents of my listOfNeighbours, generated in another of my functions:

[2, 4, 1, 6]

I don't understand the Python documentation on this, doesn't really make it sound easy for a beginner

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

客…行舟 2024-10-29 00:47:36
for nodeIndex in theNetwork:

不会使 nodeIndex 迭代 theNetwork 中的索引,而是迭代其元素的。你应该使用

for nodeIndex,node in enumerate(theNetwork):
    # theNetwork[nodeIndex] is now known as node
for nodeIndex in theNetwork:

does not make nodeIndex iterate over indices in theNetwork, but over the values of its elements. You should use

for nodeIndex,node in enumerate(theNetwork):
    # theNetwork[nodeIndex] is now known as node
锦上情书 2024-10-29 00:47:36

通过在控制台上打印来检查 theNetwork 变量:

print(theNetwork)

它可能是一个列表列表,而您希望它成为一个整数列表(为了使用其各个项目作为索引)。

Check your theNetwork variable by printing it at your console:

print(theNetwork)

It could be a list of lists, and what you are wanting it to be (in order to use its individual items as indicies) is for it to be a list of ints.

硪扪都還晓 2024-10-29 00:47:36

listOfNeighbors 是一个列表,索引从零开始。因此,listOfNeighbors[0] = 2,listOfNeighbors[1] = 4。该错误告诉您,用作访问 listOfNeighbors 中项目的索引的 nodeIndex 是一个列表,而不是预期的整数值。这意味着 theNetwork 必须由列表组成。您可以在为 currentDistance 分配值之前尝试“打印 nodeIndex”以查看它的组成部分。另外,我也没有看到您在上述函数中定义“node”或“indexNode”的位置。

另外,只是想澄清一下——这是您最终将传递给 map 的函数吗?我在函数中的任何地方都没有看到地图调用。

listOfNeighbors is a list, indexed from zero. So, listOfNeighbors[0] = 2, listOfNeighbors[1] = 4. The error is telling you that nodeIndex, which you're using as indices to access the items in listOfNeighbors, is a list -- not an integer value as expected. Which means that theNetwork must be comprised of lists. You can try a "print nodeIndex" prior to assigning a value to currentDistance to see what it's comprised of. Also, I don't see where you define "node" or "indexNode" in the above function, either.

Also, just to clarify -- is this a function you will ultimately pass to map? I don't see a map call anywhere in the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文