开篇
记录一些常用的一些python函数、模块、技巧之类的
map函数
接受一个迭代参数
In [1]: def func(x):
...: return x*x
...:
In [2]: m = map(func,range(1,8))
In [3]: m
Out[3]: <map at 0x7f58cf96d0b8>
In [4]: print(list(m))
[1, 4, 9, 16, 25, 36, 49]
接受两个参数
In [5]: def func(x,y):
...: return x+y
...:
In [6]: m = map(func,range(1,8),range(3,6))
In [7]: list(m)
Out[7]: [4, 6, 8]
按最少的元素来算
Reduce函数
注意这边的mapreduce和分布式的没有太大的关系
In [10]: from functools import reduce
In [11]: def add(x,y):
...: return x+y
...:
In [12]: m = reduce(add,range(1,6))
In [13]: m
Out[13]: 15
这边需要导入函数,上面的函数是实现连加,reduce接受的是两个参数,函数的参数也是两个
高级特性
Python语言的一些高阶用法主要有以下几个特性:
generators生成器用法
collections包常见用法
itertools包常见用法
packing/unpacking封包/解包特性
Decorators装饰器
Context Managers上下文管理期
generators生成器用法
generator一般用来产生序列类型的值得对象,一般都可以在for循环中迭代,也可以通过next方法调用,生成器可以通过yield关键字产生。
生成器的作用:
- 减少内存占用
比如:利用迭代器的使用方式打开文件
with open("/path/to/file") as f:
for line in f: # 这个地方迭代文件
print(line)
- 提高运行效率
- 延迟运行,仅当需要运行的地方才开始执行
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Print all the numbers of the Fibonacci sequence that are lower than 1000
for i in fibonacci_generator():
if i > 1000:
break
print(i)
输出结果
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
在Python中可以使用生成器表达式去迭代一个对象,生成器表达式和列表最大的差别就在于是否一次性将结果计算完成,举例如下:
a = (x * x for x in range(100))
# a is a generator object
print(type(a))
# Sum all the numbers of the generator
print(sum(a))
# There are no elements left in the generator
print(sum(a))
输出结果如下:
<class 'generator'>
328350
0
这边如果是列表的话,那么两次输出的结果就是一样的。
collections
这是我最常使用到的一个包,因为我经常使用它来统计词频,collections包是标准库的一个模块,主要目的是用来扩展容器相关的数据类型,我们通过dir查看collections包有哪些模块:
>>> import collections
>>> dir(collections)
['Callable', 'Container', 'Counter', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'OrderedDict', 'Sequence', 'Set', 'Sized', 'ValuesView', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_abcoll', '_chain', '_class_template', '_eq', '_field_template', '_get_ident', '_heapq', '_imap', '_iskeyword', '_itemgetter', '_repeat', '_repr_template', '_starmap', '_sys', 'defaultdict', 'deque', 'namedtuple']
Counter
from collections import Counter
a = Counter('blue')
b = Counter('yellow')
print(a)
print(b)
print((a + b).most_common(3))
输出结果
Counter({'u': 1, 'e': 1, 'l': 1, 'b': 1})
Counter({'l': 2, 'y': 1, 'e': 1, 'o': 1, 'w': 1})
[('l', 3), ('e', 2), ('y', 1)]
defaultdict
defaultdict是dict的子类,允许我们通过工厂方法来动态创建不存在的属性,举例如下:
from collections import defaultdict
my_dict = defaultdict(lambda: 'Default Value')
my_dict['a'] = 42
print(my_dict['a'])
print(my_dict['b'])
运行结果如下:
from collections import defaultdict
my_dict = defaultdict(lambda: 'Default Value')
my_dict['a'] = 42
print(my_dict['a'])
print(my_dict['b'])
用defaultdict来构造一颗树形数据结构
from collections import defaultdict
import json
def tree():
"""
Factory that creates a defaultdict that also uses this factory
"""
return defaultdict(tree)
root = tree()
root['Page']['Python']['defaultdict']['Title'] = 'Using defaultdict'
root['Page']['Python']['defaultdict']['Subtitle'] = 'Create a tree'
root['Page']['Java'] = None
print(json.dumps(root, indent=4))
运行结果如下:
{
"Page": {
"Python": {
"defaultdict": {
"Subtitle": "Create a tree",
"Title": "Using defaultdict"
}
},
"Java": null
}
}