Home >Backend Development >Python Tutorial >Python commonly used built-in functions and their usage

Python commonly used built-in functions and their usage

PHPz
PHPzforward
2023-04-24 08:13:061940browse

1. abs()

abs() is used to return the absolute value of a number.

In python, for built-in numerical types (int, float or complex), you can directly use the abs() function to find their absolute value. But for a custom type of numeric type, if you want to use the abs() function to find its absolute value, you need to implement the __abs__() method. The implementation of the

abs() method is also very simple. You only need to define a method named __abs__() in the class and return the absolute value of the number. . For example:

class MyNumber:
    def __init__(self, num):
        self.num = num
    
    def __abs__(self):
        return abs(self.num)

n = MyNumber(-3)
print(abs(n))    # 输出结果为:3

In the above code, we define a class named MyNumber, which contains a num attribute and implements __abs__( )method. In the __abs__() method, we call the abs() function to find the absolute value of the number.

Finally, we instantiated a MyNumber object and passed in a negative number as a parameter. Then, we called the abs() function to calculate the absolute value of the MyNumber object, and got the result 3.

2. The aiter() function

aiter() is a function in the asyncio library, used to generate asynchronous iterator objects. Python3.10 new version features.

Asynchronous iterator object is an iterator object that can be traversed asynchronously. Through asynchronous iterators, we can asynchronously obtain the elements in the iterator one by one.

aiter() Accepts an iterable object as a parameter and returns an asynchronous iterator object. Async iterator objects are instances of the AsyncIterator class.

The following is the basic syntax of the aiter() function:

asyncio.aiter(iterable, /)

Among them, iterable is an iterable object, which can be any object that supports asynchronous Iterable objects, such as asynchronous generators, asynchronous lists, etc.

When using an asynchronous iterator, we need to use the async for statement for asynchronous iteration, as shown below:

async def my_func():
    async for i in my_async_iterable:
        print(i)

In the above example, my_async_iterable It can be an asynchronous iterator object generated by the aiter() function, or it can be other objects that support asynchronous iteration.

It should be noted that after the asynchronous iterator is traversed, we need to explicitly close the asynchronous iterator object to release the corresponding resources, as shown below:

async def my_func():
    async with aiter(my_async_iterable) as iter_obj:
        async for i in iter_obj:
            print(i)

Pass## The #async with statement creates an asynchronous context manager that can automatically close the asynchronous iterator. This method is relatively simple and is recommended.

3. The all() function

is used to determine whether all elements in an iterable object are True.

The syntax format is as follows:

all(iterable)

Among them, iterable is an iterable object, such as a list, tuple, set, string, etc.

The return result is a Boolean value. If all elements in iterable are True, it returns True, otherwise it returns False. Returns True if iterable is empty.

Example:

>>> all([True, True, False, True])
False

>>> all([1, 2, 3, 4])
True

>>> all(('a', 'b', 'c'))
True

>>> all(['', [], {}])
False

In the above example, one element in the first list is False, so False is returned. All elements in the second list are non-zero values, so True is returned. Both tuples and lists can be passed to the all() function as iterable objects. The last list contains empty sequences or dictionaries, so False is returned. Note that empty lists, tuples, sets, strings, etc. will all return True.

Note:

  • If there are elements in the given iterable object that are false values ​​such as False, 0, '', None, etc., the all() function will also will return False.

  • You can use the any() function to determine whether there is at least one element that is True in the iterable object.

4. anext()

anext() is a function in the asyncio module, used to get the next value from an asynchronous iterator. If the asynchronous iterator has ended, anext() will raise a StopAsyncIteration exception.

Python3.10 new version features.

In asyncio, an asynchronous iterator (async iterator) is defined as an object that implements the __aiter__() and __anext__() methods. The

aiter() method returns the iterator object itself, the anext() method returns the next value, and if no more values ​​are available, a StopAsyncIteration exception is raised.

The following is an example of using the anext() function:

import asyncio

async def async_generator(): yield 1 yield 2 yield 3
async def main( ): ag = async_generator() try: while True:

        value = await asyncio.anext(ag)
        print(value)
except StopAsyncIteration:
    pass
asyncio.run(main())

The above code creates an asynchronous generator async_generator(), which generates The device returns 1, 2, and 3 one by one. In the main() function, we use the anext() function to get the next value from the async generator until the StopAsyncIteration exception is raised. In this example, we use the asyncio.run() function to run the main() coroutine, which uses Python 3.7 and above.

5. any() function

is used to determine whether there is at least one element in an iterable object that meets the conditions. This function returns a Boolean value, True if there is an element that meets the condition, False otherwise.

The following is the syntax format of any() function:

any(iterable)

其中iterable是一个可迭代对象,例如列表、元组、集合或字典的键等等。

any()函数的工作原理如下:

  • 遍历可迭代对象中的所有元素。

  • 对于每个元素,将其作为参数传递给判断函数,判断函数返回True或False。

  • 如果存在任意一个元素使得判断函数返回True,则返回True,并停止遍历,否则返回False。

下面是一个示例,演示如何使用any()函数来判断一个列表中是否存在奇数:

lst = [2, 4, 6, 8, 9, 10]
result = any(x % 2 == 1 for x in lst)
print(result)

输出:

True

在上面的示例中,我们使用生成器表达式来表达“是否存在奇数”这个条件。这个表达式对于lst中的每个元素x都执行一次,如果x % 2 == 1返回True,则any()函数会立即返回True。因为9是lst中的一个奇数,所以any()函数返回True。

除了列表,any()函数也适用于其他可迭代对象。例如,我们可以使用any()函数来检查一个字符串中是否存在大写字母:

s = "Hello, World!"
result = any(c.isupper() for c in s)
print(result)

输出:

True

在上面的示例中,我们使用字符串的isupper()方法来判断每个字符是否为大写字母,如果存在任意一个字符是大写字母,则any()函数返回True。因为"H"是一个大写字母,所以any()函数返回True。

在使用any()函数时,需要注意以下几点:

  • 如果iterable为空,any()函数将返回False。

  • 如果iterable中的所有元素都为假值(例如0、空字符串或空列表),则any()函数将返回False。

六、ascii()函数

用于将给定字符串或对象的表示转换为ASCII码。如果给定对象不是字符串,则会先将其转换为ASCII码表示。如果给定字符串中包含了非ASCII字符,则会使用Python的转义序列来表示这些字符。

以下是ascii()函数的语法:

ascii(object)

其中,object是要转换为ASCII码表示的字符串或对象。

以下是ascii()函数的示例:

s = 'hello, 你好!'
print(ascii(s)) 
# 输出: 'hello, \u4f60\u597d\uff01'

n = 1234
print(ascii(n)) 
# 输出: '1234'

lst = [1, 2, 'hello', '你好']
print(ascii(lst)) 
# 输出: '[1, 2, \'hello\', \'\\u4f60\\u597d\']'

在以上示例中,第一个示例中的字符串包含了一个非ASCII字符,因此在转换为ASCII码表示时使用了Python的转义序列;第二个示例中的对象是一个整数,因此可以直接转换为ASCII码表示;第三个示例中的对象是一个列表,其中包含了一个非ASCII字符串,因此在转换为ASCII码表示时使用了Python的转义序列。

注意事项

  • ascii()函数只能处理字符串类型的输入,对其他类型的对象(如数字、列表、元组、字典等)会引发TypeError异常。

  • ascii()函数只能处理ASCII字符以外的非ASCII字符,对于ASCII字符,它不做任何处理。(ASCII字符是指Unicode编码为0~127的字符,包括所有的英文字母、数字、标点符号和控制字符。)

  • ascii()函数返回的ASCII码表示是一个字符串,如果需要使用对应的Unicode码,可以使用Python内置的ord()函数。

The above is the detailed content of Python commonly used built-in functions and their usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete