Python列表如何按索引删除adjListCopy中的列表元素?

2024-04-26 02:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

adjList = [[1,2,3,7], [2,1,3,7], [3,1,2,4], [4,3,5,6], [5,4,6], [6,4,5], [7,1,2]]
adjListCopy= adjList[:]
v=int(raw_input("Enter the node v to be deleted along with its neighbourhood"))
copy = adjList[v-1]
print(copy)
del adjList[v-1]
print adjList
print adjListCopy

输出:

Enter the node v to be deleted along with its neighbourhood2
[2, 1, 3, 7]
[[1, 2, 3, 7], [3, 1, 2, 4], [4, 3, 5, 6], [5, 4, 6], [6, 4, 5], [7, 1, 2]]
[[1, 2, 3, 7], [2, 1, 3, 7], [3, 1, 2, 4], [4, 3, 5, 6], [5, 4, 6], [6, 4, 5], [7, 1, 2]]
print adjListCopy
for i in range(len(copy)):
    print(copy[i])
    for j in range(len(adjListCopy)):
        if copy[i]==adjListCopy[j][0]:
            print adjListCopy[j] ***************
print adjListCopyFor1

在我做******的地方,我想写del而不是print来解决我的目的,但它抛出了一个错误。你知道吗


Tags: thetonodeforwithbeitsprint
3条回答

我现在在打电话。但是我可以告诉你,当你迭代或者循环一个列表时,你不能删除索引。您可以获取列表的副本(copy.deepcopy),对副本进行迭代,然后按索引从原始列表中删除。你知道吗

您不应该删除正在迭代的列表中的元素。我认为你应该del adjList[i]而不是adjListCopy[j]。否则,可以迭代adjList(for j in range(len(adjList)):)并从adjListCopy中删除。你知道吗

您不能只删除范围(len(adjListCopy)),因为删除元素时大小会发生变化,您应该执行以下操作:

j = 0
while j < len(adjListCopy):
    if copy[i]==adjListCopy[j][0]:
        del adjListCopy[j]
    else:
       j++

相关问题 更多 >