How to gracefully judge multiple conditions at one time in python
This article mainly introduces how to elegantly judge multiple conditions at one time in python. The introduction in the article is very detailed and has certain reference value. Interested friends must read it!
Elegant one-time judgment of multiple conditions
If there are three conditions, and only one of them is true, you might write:
x, y, z = 0, 1, 0 if x == 1 or y == 1 or z == 1: print('passed')
In fact, the following three methods are more Pythonic.
if 1 in (x, y, z): print('passed') if x or y or z: print('passed') if any((x, y, z)): print('passed')
The last one uses Python's built-in method any(), which takes an iterable object as an argument, such as a list or tuple, and returns true if one of them is true. Examples of usage are as follows:
>>> any(['a',(2,4),3,True]) True >>> any(['a',(2,4),3,False]) True >>> any(['a',(),3,False]) True >>> any(['',(),0,False]) False >>> any(('a ',(),3,False)) True >> any(('',(),0,False)) False ##Note Empty iterable objects return False >> any (()) False >> any([]) False >> any ('') False>> any({}) False
The corresponding to any() is the method all(), which is true only if all are true. Note that empty iterable objects always return true.
>>> all(['a',(2,4),1,True]) //list is "True">> all(['a',(),1,True]) //empty tuple False >> all(<$'a ',(2,4),0,True]) False >> all(<$'a',(2,4),3,False]) False ##Note Empty iterable objects return True >>all([]) True >> all (()) True >> all({}) True >> all ('') True
To view the help documentation, type help in the interpreter:
>>> help(all) Help on built-in function all in module __builtin__: all(...) all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. The above is "How to elegantly judge multiple conditions at once in python" All the contents of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!