记录一些Python使用方法,方便日后查阅。
文件读写
JSON文件
1 | #文件中每一行都是字典格式的数据 |
数组
获取元素的索引
1 | name1 = ['python', 'java', 'php', 'MySql', 'C++', 'C', 'php', 'C#'] |
排列组合枚举
列表
1 | import itertools |
计数
1 | from collections import Counter |
多进程
1 | res = [] |
进程卡死
系统环境 Ubuntu 20.04,Python 3.7
在处理比较大的数据(百万级别)时,上面的的程序会卡死,即数据已处理完,但是程序没有退出。可能是因为同时处理太多数据出现进程死锁1。
解决方法
分批处理,既然不能同时处理大量数据,可以设置为每处理完一部分数据(比如10%)就通过pool.close()
和pool.join()
结束当前批量数据的处理,处理完再开启多进程处理下一批。
更正:我遇到的进程卡死的情况,最后查出的原因是部分极端数据导致程序计算复杂度非常高 $O(n!)$, 一直在该处运行导致部分进程一直没退出看起来像卡死。不过最好还是分批处理,这样可以减少
参考
[1] Python doc
[2] Why your multiprocessing Pool is stuck (it’s full of sharks!)
类
特殊属性和方法
repr()方法:显示属性
通常情况下,直接输出某个实例化对象,得到的信息只会是“类名+object at+内存地址”。
1 | class Posting(object): |
hasattr
Syntax : hasattr(obj, key)
Parameters :
- obj : The object whose which attribute has to be checked.
- key : Attribute which needs to be checked.
Returns : Returns True, if attribute is present else returns False.
判断obj是否有属性key
getattr
Syntax : getattr(obj, key, def)
Parameters :
- obj : The object whose attributes need to be processed.
- key : The attribute of object
- def : The default value that need to be printed in case attribute is not found.
Returns : Object value if value is available, default value in case attribute is not present
and returns AttributeError in case attribute is not present and default value is not
specified.