Files
ailearning/docs/da/077.md
2020-10-19 21:08:55 +08:00

174 lines
2.9 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# operator, functools, itertools, toolz, fn, funcy 模块
## operator 模块
In [1]:
```py
import operator as op
```
`operator` 模块提供了各种操作符(`+,*,[]`)的函数版本方便使用:
加法:
In [2]:
```py
print reduce(op.add, range(10))
```
```py
45
```
乘法:
In [3]:
```py
print reduce(op.mul, range(1,10))
```
```py
362880
```
`[]`
In [4]:
```py
my_list = [('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)]
# 标准排序
print sorted(my_list)
# 使用元素的第二个元素排序
print sorted(my_list, key=op.itemgetter(1))
# 使用第一个元素的长度进行排序:
print sorted(my_list, key=lambda x: len(x[0]))
```
```py
[('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)]
[('a', 1), ('ccc', 2), ('dddd', 3), ('bb', 4)]
[('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)]
```
## functools 模块
`functools` 包含很多跟函数相关的工具,比如之前看到的 `wraps` 函数,不过最常用的是 `partial` 函数,这个函数允许我们使用一个函数中生成一个新函数,这个函数使用原来的函数,不过某些参数被指定了:
In [5]:
```py
from functools import partial
# 将 reduce 的第一个参数指定为加法,得到的是类似求和的函数
sum_ = partial(reduce, op.add)
# 将 reduce 的第一个参数指定为乘法,得到的是类似求连乘的函数
prod_ = partial(reduce, op.mul)
print sum_([1,2,3,4])
print prod_([1,2,3,4])
```
```py
10
24
```
`partial` 函数还可以按照键值对传入固定参数。
## itertools 模块
`itertools` 包含很多与迭代器对象相关的工具,其中比较常用的是排列组合生成器 `permutations``combinations`,还有在数据分析中常用的 `groupby` 生成器:
In [6]:
```py
from itertools import cycle, groupby, islice, permutations, combinations
```
`cycle` 返回一个无限的迭代器,按照顺序重复输出输入迭代器中的内容,`islice` 则返回一个迭代器中的一段内容:
In [7]:
```py
print list(islice(cycle('abcd'), 0, 10))
```
```py
['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b']
```
`groupby` 返回一个字典,按照指定的 `key` 对一组数据进行分组,字典的键是 `key`,值是一个迭代器:
In [8]:
```py
animals = sorted(['pig', 'cow', 'giraffe', 'elephant',
'dog', 'cat', 'hippo', 'lion', 'tiger'], key=len)
# 按照长度进行分组
for k, g in groupby(animals, key=len):
print k, list(g)
print
```
```py
3 ['pig', 'cow', 'dog', 'cat']
4 ['lion']
5 ['hippo', 'tiger']
7 ['giraffe']
8 ['elephant']
```
排列:
In [9]:
```py
print [''.join(p) for p in permutations('abc')]
```
```py
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
```
组合:
In [10]:
```py
print [list(c) for c in combinations([1,2,3,4], r=2)]
```
```py
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
```
## toolz, fn 和 funcy 模块
这三个模块的作用是方便我们在编程的时候使用函数式编程的风格。