【问题标题】:Object list index is not being updated: Index Error: list对象列表索引未更新:索引错误:列表
【发布时间】:2017-08-30 09:16:37
【问题描述】:

我有一门课,我会省略不重要的信息:

class BuildMap:
def __init__(self):
    #Constructor
    self.nodes = []

def indexmap(self):
        for node in self.nodes:
            print(int(node),":",nodes[node])

def delnode(self,num):
    del self.nodes[num]
    for edge in self.edges:
        if num in self.edges[edge]:
            self.edges[edge].remove(num)
    del self.edges[num] #Deletes the list associated with the number
    del nodes[int(num)] #Deleted the word associated with the node number
    for dist in list(self.distance.keys()):
        if num in dist:
            del self.distance[dist]

课外:

def delnode():
    print("Please specify the city you would like to remove: ")
    GPSMap.indexmap()
    num = input("City Number: ")
    if int(num) >= len(nodes):
        print("Sorry that number does not match")
        delnode()
    GPSMap.delnode(int(num))

我遇到的问题是,在删除一个“节点”并完成我为清理收到的其他数据结构而编写的所有代码之后

File "C:/Users/gibbo/PycharmProjects/main.py", line 52, in indexmap
print(int(node),":",nodes[node])
IndexError: list index out of range

我已经进行了一些调试,发现我的索引并没有随着列表的长度而停止,并且在节点被删除之后就过去了,就好像索引没有被更新或者我的 for 循环一样:

for node in self.nodes:

不使用列表中的节点数作为索引。

【问题讨论】:

  • nodes[node] 应该是 self.nodes[node] 在 ~8 行中
  • node 已经是一个节点,而不是一个索引;你不需要通过nodes[node]self.nodes[node] 来获取节点。
  • @ryugie 应该澄清这个节点是不同的,它是一个名称列表,我想将节点(数字)映射到节点(名称),所以索引是 1:1
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。您发布的代码缩进不当;即使已解决,也不会重现问题。

标签: python python-3.x class for-loop indexing


【解决方案1】:

node 是一个node,而不是一个整数。由于您没有包含对象的定义,因此我们不知道将其转换为整数时会发生什么,但我很确定您不会喜欢这个结果。当您将其用作索引时,结果几乎肯定会超出您的列表范围。

要查看实际效果,请将您的打印语句分开:

print(int(node))
print(nodes[node])

总的来说,您应该认识到 node 是列表中的节点,而不是它在列表中的位置。直接使用node作为你想要的对象。

【讨论】:

  • 节点索引如下: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 我选择使用节点而不是数字是因为如果我从列表中删除了say '3',所以我会得到节点在列表中的位置,但我认为情况并非如此。
【解决方案2】:
def indexmap(self):
        for node in self.nodes:
#  list elem -^      ^- list
            print(int(node),":",nodes[node])
#                                      ^- It should be int, not elem.

所以,修复它。

def indexmap(self):
    for (i,node) in enumerate(self.nodes):
        print("{}:{}".format(i, node))

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 2016-05-09
    • 2014-08-11
    • 2023-04-05
    • 2021-05-12
    相关资源
    最近更新 更多