编码
- 写入json文件时出现的编码问题和缩进问题
with codecs.open('result.json', 'w', encoding='utf8') as json_file:
json_file.write(json.dumps(item, ensure_ascii=False, indent=2))
列表
- 子列表合并
In [199]: l=[[1,2,3], [3,5,6], [7,8,9]]
In [200]: reduce(lambda x,y:x+y, l)
Out[200]: [1, 2, 3, 3, 5, 6, 7, 8, 9]
- 匹配最相似的
从一堆list中找一个与目标list最相似的,相同项越多可以视为越相似
In [211]: s={5,6,7}
In [212]: ls=[{1,2,3}, {3,4,5}, {4,5,6}]
In [213]: sorted(ls, key=lambda x: set(x)&set(s), reverse=True)[0]
Out[213]: {4, 5, 6}
itertools模块
- 排列组合的实现
In [217]: from itertools import combinations, permutations
...: print(permutations([1, 2, 3], 2))
...: print(list(permutations([1, 2, 3], 2)))
...: print(list(combinations([1, 2, 3], 2)))
...:
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
[(1, 2), (1, 3), (2, 3)]
pip
- 换源
永久
修改 ~/.pip/pip.conf (没有就创建一个),内容如下:
[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple临时
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gevent