# Python常用的8个高级函数

Python爬虫、数据分析、网站开发等案例教程视频免费在线观看

``````https://space.bilibili.com/523606542
``````

### lambda

`lambda argument: manipulate(argument)`

`lambda 参数:操作(参数)`

``````add = lambda x, y: x + y

# 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)
``````

key 指定一个带有一个参数的函数，用于从每个列表元素中提取比较键：`key=str.lower`。默认值是 `None`（直接比较元素）。

reverse 是一个布尔值。如果设置为 `True`，那么列表元素按照每个比较被颠倒的顺序进行排序。

### 三元表达式

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

### map

map(function, iterable, ...)

``````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( iterable, start=0)

``````>>> 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)

`*` 操作符一起使用 `zip()` 可用于解压缩列表：

``````>>> 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)

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

### reduce

reduce函数的用法和map很类似,也是一个函数f和一个list,但是函数的入口参数一定要是两个，reduce也是对每个元素进行反复调用，最后返回最终的值，而map是返回一个list

python3里面reduce已经从全局函数里面移除了，需要用的话要 from functools import reduce