I regret not knowing how to use the Python any() function

This article mainly introduces the use of Python any() function. The introduction is very detailed through the sample code. It has a certain reference learning value for everyone's study or work. Friends who need it will follow the editor to learn and study together. Bar

description:

If any element of iterable is true, return true. If iterable is empty, it returns false. Is equivalent to:

def any(iterable):
  for element in iterable:
    if element:
      return True
  return False

Meaning: to determine whether a tuple or list is all empty, 0, or False. If all are empty, 0, False, then return False; if (as long as there are non-[empty or 0 or False]) are not all empty, 0, False, then return True. 

Note: The return value of empty tuple (parentheses) and empty list (brackets), empty dictionary empty set (curly brackets) is False.

grammar:

any(iterable)

Parameter introduction:

iterable---iterable, including string, list, dict, tuple, set()

return value:

The following example shows how to use the any() function

print(any([1,2,3,4,5])) # 列表list,元素都不为空或0。True
print(any(['a','b','c','d',''])) # 列表list,存在一个为空的元素。True
print(any([1,2,3,0,5]))  # 列表list,存在一个为0的元素。True
print(any([0,False,'']))  # # 列表list,元素全为0,'',false。False
print(any((1,2,3,4,5))) # 元组tuple,元素都不为空或0。True
print(any(('a','b','c','d',''))) # 元组tuple,存在一个为空的元素。True
print(any((1,2,3,0,5)))  # 元组tuple,存在一个为0的元素。True
print(any((0,False,'')))  # 元组tuple,元素全为0,'',false。False
print(any([])) #空列表。False
print(any(())) #空元组。False
print(any({})) #空集合空字典。False

Output

True
 True
 True
 False
 True
 True
 True
 False
 False
 False
 False

Extension: Use python to determine whether a string contains an element in a list. (The elements of list are of course also strings...)


2
3
4
 
place = ['shenzhen','guangzhou','shanghai']
str = "I want to go shenzhen"
if any(element in str for element in place): #成员运算符和推导式
  print("string contains shenzhen")
 

Output

string contains shenzhen

The above is the whole content of this article, I hope it will be helpful to everyone's study.

I am a python development engineer, and I have compiled a set of the latest python system learning tutorials, including basic python scripts to web development, crawlers, data analysis, data visualization, machine learning, and interview books. Those who want these materials can pay attention to the editor, add Q skirt 851211580 to pick up Python learning materials and learning videos, and online guidance from the Great God!

Guess you like

Origin blog.csdn.net/pyjishu/article/details/105432500