Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Introduce four python functions that are commonly used by great gods but not commonly used by you

Shulou Source: shulou.com Published: 2022-06-03 00:16:02 10月01日 Update

Introduce four python functions that are commonly used by great gods but not commonly used by you

Https://mp.weixin.qq.com/s/C2nw4JShmj1FlLeDy0IeRA

Today, we will talk about four functions: assert, map,filter,reduce.

Assert

Commonly known as assertion! That is to say, to assert a thing, if it is true, the program will continue; if it is false, an error will be reported.

How to use it?

Two uses

Assert

Assert

First kind

Def avg (marks):

Assert len (marks)! =

Return sum (marks) / len (marks)

Mark1 = []

Print ("Average of mark1:", avg (mark1))

The result is

AssertionError

The second kind

Def avg (marks):

Assert len (marks)! =, "List is empty."

Return sum (marks) / len (marks)

Mark2 = [55, 88, 78, 90, 79]

Print ("Average of mark2:", avg (mark2))

Mark1 = []

Print ("Average of mark1:", avg (mark1))

The result is

Average of mark2: 78.0

AssertionError: List is empty.

Map

In many cases, we perform the same operation on the data in a list, such as:

Items = [1,2,3,4,5]

Squared = []

For i in item s:

Squared. Append (iTunes * 2)

At this point, you can use map operation in the format:

Map (function_to_apply, list_input)

The specific operation is

Items = [1,2,3,4,5]

Squared = list (map (lambda x: Xerox * 2, items))

Of course, functions can be put in list.

Def multiply (x):

Return (xonomx)

Def add (x):

Return (xonomx)

Funcs = [multiply, add]

For i in range (5):

Value = list (map (lambda x: X (I), funcs))

Print (value)

# Output:

# [0, 0]

# [1, 2]

# [4, 4]

# [9, 6]

# [16, 8]

Of course, you can also perform str2id operations.

A = ['5','2','3','4','5']

Print (list (map (int, a)

# [5, 2, 3, 4, 5]

Filter

The filter function is to filter and filter a given condition.

Number_list = range (- 5,5)

Less_than_zero = list (filter (lambda x: X)

Tags: Function that is result common use time network big god huge no need deposit that is huge data condition format neural neural network program part bank. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn OPPO Reno Shulou Information MariaDB macOS