Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to gracefully judge multiple conditions at one time in python

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report