¿Puede alguien por favor ayudarme a cerrar mi brecha en la comprensión?
¿Por qué es necesaria la variable 'índice' para 'bajar' una fila en una lista de listas? Pensé que un bucle for lo hacía automáticamente.
#I am working with the following data url = "https://en.wikipedia.org/wiki/List_of_helicopter_prison_escapes" data = data_from_url(url) for row in data[:3]: #I use this because I have to get rid of the information in the column named 'Details' print(row) #"The assignment says: Initialize an index variable with the value of 0. The purpose of this variable is to help us track which row we're modifying." - (I don't get this explanation) index = 0 for row in data: data[index] = row[:-1] index += 1 #Why is the following code not enough if a 'for loop' iterates through each row in a list of lists? for row in data: data= row[:-1]Probemos ambos a ver que pasa:
>>> data = [[1,2,3],[4,5,6],[7,8,9]] >>> index = 0 >>> for row in data: ... data[index] = row[:-1] ... index += 1 ... >>> data [[1, 2], [4, 5], [7, 8]]Se ve bien; todas las filas sin sus últimos elementos.
>>> data = [[1,2,3],[4,5,6],[7,8,9]] >>> for row in data: ... data = row[:-1] ... >>> data [7, 8] Vaya, esa es solo la última fila sin su último elemento, ya que eso es lo que asignó a data .
Sin embargo, existen métodos menos complicados y propensos a errores para realizar la tarea sin recurrir a la indexación.
Por ejemplo,
>>> data = [[1,2,3],[4,5,6],[7,8,9]] >>> data = [it[:-1] for it in data] >>> data [[1, 2], [4, 5], [7, 8]]