manejo de errores con listas de python

I have lists being created by a program and depending if a value exists I want to do something further. If not, I want to pass.

Por ejemplo:


if a.index(6):
    print "in"

Obtengo lo siguiente

Traceback (most recent call last):
  File "", line 6, in <module>
    if a.index(6):
ValueError: 6 is not in list

How do I search for a value in a python list and do something if I find the number?

preguntado el 29 de septiembre de 13 a las 22:09

Somebody also ought to mention that if your elements are hashable and if you're planning on doing a lot of membership testing, a better data-structure might be a set: a = {1, 2, 3, 4, 5} -

3 Respuestas

you can make a condition like this:

if "a" in list:
    #do stuff

sin que importe "a" is what you're searching for in the list

if you want to do it the way you have it in youre code try a try/except bloquear así:

    #try this code
    if a.index(6):
        print "in"
except ValueError:
    #do this if there is an error

Respondido el 29 de Septiembre de 13 a las 22:09

Cobija except? Bad practice. - user2357112

No deberías usar index to test if something is in a list. index assumes the item you are searching for is already in the list. Furthermore (and as you know), if it can't find it, it throws an error. Instead, use the in palabra clave:

if value in lst:
    # value was found in lst

Vea un ejemplo:

>>> a = [1,2,3,4,5,6]
>>> 6 in a
>>> 7 in a

Entonces, su código debería ser este:


if 6 in a:
    print "in"

Respondido el 29 de Septiembre de 13 a las 23:09

if 6 in a:

in tests containment. index gives the index of something you know is in the list.

Respondido el 29 de Septiembre de 13 a las 22:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.