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来解决我的目的,但它抛出了一个错误。你知道吗
我现在在打电话。但是我可以告诉你,当你迭代或者循环一个列表时,你不能删除索引。您可以获取列表的副本(
copy.deepcopy
),对副本进行迭代,然后按索引从原始列表中删除。你知道吗您不应该删除正在迭代的列表中的元素。我认为你应该
del adjList[i]
而不是adjListCopy[j]
。否则,可以迭代adjList(for j in range(len(adjList)):
)并从adjListCopy中删除。你知道吗您不能只删除范围(len(adjListCopy)),因为删除元素时大小会发生变化,您应该执行以下操作:
相关问题 更多 >
编程相关推荐