Change index python loop


My problem is to modify the value of k. That is, when I call the function funmeta, it returns a position that I want it to acquire k and start again the top loop for that position. As it is in the code, it is not modified.

for k,i in enumerate(lista):
        valor = input("Introduce el valor de m" + i.m)
        index = funmeta(lista, i.m, valor)
            k = index
        k = index
asked by fpa 07.03.2017 в 09:29

1 answer


In these cases the easiest thing is to change the cycle for to while , so that the control variable of while is the index itself and can be modified without problems from within the cycle itself.

Since I do not know what your function funmeta() or what i.m is, I leave you an implementation with the same idea, change the iteration index within the own cycle at will when going through a list.

In this example you can change the index by returning the function getIndx using a input , if you enter a valid index the function returns this index and the loop is 'reset' by that position in the list, if it is entered otherwise, the function returns -1 and the cycle continues normally:

lista = [1,2,3,4,5,6,7,8,9,10]

def getIndx(lista):
        index = int(input("Introduce el nuevo indice, entre 0 y {0} o otra si desea continuar el ciclo: ".format(len(lista)-1)))
        if index in range(0, len(lista)):
            return index
        return -1

#A partir de aquí el código es el sustituto de tu for

k = 0
while k < len(lista):
    v = lista[k]
    print('Indice:', k, 'Valor:', lista[k])

    index = getIndx(lista)

    if index >= 0:
        k = index

If you have problems adapting it to your code, edit the question by adding the minimum code to be able to play your program.

answered by 07.03.2017 / 11:20