"Python" temporary file [to be deleted 2]

One, map function

map(function, iterable, ...)
map() will map the specified sequence according to the provided function. You can apply a function to an iterable sequence and return the sequence output by the function.
The first parameter function calls the function function with each element in the parameter sequence and returns a new list containing the return value of each function function.

# 示例
mylist = list(map(upper, ['sentence', 'fragment']))
list_of_ints = list(map(int, "1234567"))

Two, reduce function

reduce()A function map()is different from a function. The input function requires two parameters. reduce()The process is to first use the input function to operate on the first two elements in the sequence, and the result obtained is then operated on with the third element until the last element.

Three, filter function

filter()The function of the function is mainly to filter the iterable sequence through the input function and return the iterable sequence that meets the filter condition.

def is_odd(n):
	return n % 2 == 0
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
# return: [2, 4, 6, 10]

Four, sorted function

sorted()The function can complete the sorting of the iterable sequence. And the list itself comes with sort()different functions, where the sorted()function returns a new list. sorted()The function can pass in keywords keyto specify the sorting criteria, and the parameter reverserepresents whether to reverse.

sorted([3, 5, -87, 0, -21], key=abs, reverse=True)	# 绝对值排序,并且为反序
# return: [-87, -21, 5, 3, 0]

Five, lambda anonymous function

For some simple logic functions, lambdaanonymous function expressions can be used to replace Korean definitions, which can save the definition of function names and simplify the readability of the code.

add = lambda x, y: x + y
add(1, 2)
# return: 3

Guess you like

Origin blog.csdn.net/libo1004/article/details/111030433