編碼
- 寫入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)))
...:
<itertools.permutations object at 0xae84298c>
[(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