8 high-level functions commonly used in Python

Python crawler, data analysis, website development and other case tutorial videos are free to watch online

https://space.bilibili.com/523606542

lambda

They are also called anonymous functions in other languages. If you don't want to use a function twice in your program, you might want to use lambda expressions, which are exactly the same as ordinary functions.

lambda argument: manipulate(argument)

lambda parameter: operation (parameter)

add = lambda x, y: x + y

print(add(3, 5))
# Output: 8
a = [(1, 2), (4, 1), (9, 10), (13, -3)]

def f(x):
    return x[1]

# a.sort(key=f)
a.sort(key=lambda x: x[1])

print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]

sorted

sorted(iterable, *, key=None, reverse=False)

Return a new sorted list from the items in iterable.

There are two optional parameters, which must be specified as keyword parameters.

key specifies a function with one parameter to extract the comparison key from each list element: key=str.lower. The default value is None (compare elements directly).

reverse is a boolean value. If set to True, the list elements are sorted according to the order in which each comparison is reversed.

The built-in sorted() function sorting is stable. If it is ensured that the relative order of elements that compare equal is not changed, the sorting is stable.

Ternary expression

Ternary operators are usually called conditional expressions in Python. These expressions are based on true/false conditional judgments.

It allows quick judgments with a simple one line instead of complex multi-line if statements. This is very useful most of the time, and can make the code simple and maintainable.

# 如果条件为真,返回真 否则返回假
condition_is_true if condition else condition_is_false
if condition:
    result = condition_is_true
else:
    result = condition_is_false

map

map(function, iterable, ...)

Returns an iterator that applies function to each iterable item, resulting in a result. If you pass additional iterable parameters, function must take multiple parameters and apply to items in all iterations in parallel. When using multiple iterators, when the shortest iterator is exhausted, the iterator stops.

In [54]: list1 = [1, 2, 3, 4, 5, 6]

In [55]: list2 = [4, 3, 7, 1, 9]

In [56]: list(map(str, list1))
Out[56]: ['1', '2', '3', '4', '5', '6']

In [57]: list(map(lambda x, y: x+y, list1, list2))
Out[57]: [5, 5, 10, 5, 14]

enumerate

enumerate( iterablestart=0)

Returns an enumeration object. iterable must be a sequence, an iterator or other object that supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (starting from start, the default value is 0) and the value obtained by traversing the iteration.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

zip

zip(*iterables)

Make an iterator to aggregate the elements from each iterator.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each parameter sequence or iteration. When the shortest input iteration is exhausted, the iterator stops. With a single iteration parameter, it will return an iterator of 1-tuples. Without parameters, it returns an empty iterator.

Use zip() with the * operator to decompress the list:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
data = zip(list1, list2)
data = sorted(data)
list1, list2 = map(lambda t: list(t), zip(*data))

filter

filter(function, iterable)

Construct an iterator with iterable elements whose function returns true. Iterable can be a sequence, a container or iterator that supports iteration. If function is None, it is assumed that the identification function is false, that is, all elements that are false are deleted.

# 过滤0-10之间的偶数
In [8]: list(filter(lambda x: x%2==0, range(10)))
Out[8]: [0, 2, 4, 6, 8]

reduce

The usage of the reduce function is very similar to that of map. It is also a function f and a list, but the entry parameters of the function must be two . Reduce is also called repeatedly for each element, and finally returns the final value, while map returns a list.

In python3, reduce has been removed from the global function, if you need to use it, from functools import reduce

Guess you like

Origin blog.csdn.net/m0_48405781/article/details/114092565