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
Salida:
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
En el lugar donde hice ********* me gustaría escribir del en lugar de imprimir para resolver mi propósito, pero arroja un error.
4 respuestas
Actualmente estoy en mi teléfono. Pero puedo decirle que no puede eliminar índices mientras itera o recorre una lista. Puede tomar una copia (copy.deepcopy
) de la lista, iterar sobre la copia y eliminarla por el índice del original.
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
print adjListCopy
for i in range(len(copy)):
print(copy[i])
for idx,j in enumerate(adjListCopy):
if copy[i]==adjListCopy[idx][0]:
del adjListCopy[idx]
break
print adjListCopy
l1 = []
for i in range(len(adjListCopy)):
l1.append(adjListCopy[i][0])
print l1
a=1
print(l1)
result = []
for i in range(len(adjListCopy)):
l2 = []
l2.append(adjListCopy[i][0])
for j in range(1,len(adjListCopy)):
x = adjListCopy[i][j]
if x not in l1:
print("Found: ", x)
print(j)
l2.append(x)
j+=1
result.append(l2)
print('****')
print result ```
No debe eliminar un elemento de la lista sobre el que está iterando. Creo que deberías del adjList[i]
y no adjListCopy[j]
. De lo contrario, puede iterar sobre adjList (for j in range(len(adjList)):
) y eliminar de adjListCopy.
No puede simplemente iterar sobre el rango (len (adjList Copy)) porque el tamaño cambia a medida que elimina el elemento que debe hacer:
j = 0
while j < len(adjListCopy):
if copy[i]==adjListCopy[j][0]:
del adjListCopy[j]
else:
j++
Preguntas relacionadas
Nuevas preguntas
python
Python es un lenguaje de programación multipropósito, de tipificación dinámica y de múltiples paradigmas. Está diseñado para ser rápido de aprender, comprender y usar, y hacer cumplir una sintaxis limpia y uniforme. Tenga en cuenta que Python 2 está oficialmente fuera de soporte a partir del 01-01-2020. Aún así, para preguntas de Python específicas de la versión, agregue la etiqueta [python-2.7] o [python-3.x]. Cuando utilice una variante de Python (por ejemplo, Jython, PyPy) o una biblioteca (por ejemplo, Pandas y NumPy), inclúyala en las etiquetas.