Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
¿Cuál es la forma más pitónica de verificar si varias variables no son Ninguna?

Si tengo una construcción como esta:

 def foo(): a=None b=None c=None #...loop over a config file or command line options... if a is not None and b is not None and c is not None: doSomething(a,b,c) else: print "A config parameter is missing..."

¿Cuál es la sintaxis preferida en python para verificar si todas las variables están configuradas en valores útiles? ¿Es como he escrito, o de otra manera mejor?

Esto es diferente de esta pregunta: no hay prueba de Ninguna en Python ... Estoy buscando el método preferido para verificar si muchas condiciones no son Ninguna. La opción que he escrito parece muy larga y no pitónica.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Se puede hacer mucho más simple, de verdad.

 if None not in (a, b, c, d): pass

ACTUALIZAR:

Como ha señalado correctamente slashCoder, el código anterior implícitamente hace a == Ninguno, b == Ninguno, etc. Esta práctica está mal vista. El operador de igualdad se puede sobrecargar y no Ninguno puede volverse igual a Ninguno. Usted puede decir que nunca sucede. Bueno, no lo hace, hasta que lo hace. Entonces, para estar seguro, si desea verificar que ninguno de los objetos sea Ninguno, puede usar este enfoque

 if not [x for x in (a, b, c, d) if x is None]: pass

Es un poco más lento y menos expresivo, pero sigue siendo bastante rápido y corto.

over 4 years ago · Santiago Trujillo Report

0

No hay nada de malo en la forma en que lo estás haciendo.

Si tiene muchas variables, puede ponerlas en una lista y usarlas all :

 if all(v is not None for v in [A, B, C, D, E]):
over 4 years ago · Santiago Trujillo Report

0

Sé que esta es una pregunta antigua, pero quería agregar una respuesta que creo que es mejor.

Si todos los elementos que deben verificarse son hashable, puede usar un conjunto en lugar de una lista o tupla.

 >>> None not in {1, 84, 'String', (6, 'Tuple'), 3}

Esto es mucho más rápido que los métodos en las otras respuestas.

 $ python3 -m timeit "all(v is not None for v in [1, 84, 'String', (6, 'Tuple'), 3])" 200000 loops, best of 5: 999 nsec per loop $ python3 -m timeit "None not in [1, 84, 'String', (6, 'Tuple'), 3]" 2000000 loops, best of 5: 184 nsec per loop $ python3 -m timeit "None not in (1, 84, 'String', (6, 'Tuple'), 3)" 2000000 loops, best of 5: 184 nsec per loop python3 -m timeit "None not in {1, 84, 'String', (6, 'Tuple'), 3}" 5000000 loops, best of 5: 48.6 nsec per loop

Otra ventaja de este método es que te da la respuesta correcta incluso si alguien define el método __eq__ de una clase para que siempre devuelva True . (Por supuesto, si definen el método __hash__ para return hash(None) , este método no funcionará. Pero nadie debería hacer eso, porque anularía el propósito de definir un hash).

 class my_int(int): def __init__(self, parent): super().__init__() def __eq__(self, other): return True def __hash__(self): return hash(super()) print(all(v is not None for v in [1, my_int(6), 2])) # True (correct) print(None not in [1, my_int(6), 2]) # False (wrong) print(None not in (1, my_int(6), 2)) # False (wrong) print(None not in {1, my_int(6), 2}) # True (correct)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!