好久没有更新关于Python的小知识点的文章了,一方面是因为过年期间事情多,另一方面就是好像没怎么总结了,所以不知道该写些什么,最近碰到了些就马上记下来了,否则以后碰到了还是不知道……
1.Python中圆括号、方括号和大括号的区别
搜索关键字:
http://search.aol.com/aol/search?q=Python+%27square+bracket%27+brace
实际测试(使用IPython):
结论:
- () #元组(但在单一元素的情况下记得在最后添加一个逗号’,’,否则会出错)
- [] #列表
- {} #字典、集合
参考链接:
2.Python中的in关键字的效率
搜索关键字:
http://search.aol.com/aol/search?q=python+in+dict+efficiency
参考结论:
Sets: Operation | Example | Complexity | Notes --------------+--------------+------------+----------------------- Containment | x in/not in s| O(1) | compare to list/tuple - O(N)
使用dict或set而不是list/tuple;
即(使用大括号而不是圆括号):
使用:if mac_addr in {eth_addr(packet[0:6]), eth_addr(packet[6:12])}:
而不是:if mac_addr in (eth_addr(packet[0:6]), eth_addr(packet[6:12])):
原因参考第1点。
参考链接:
- http://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table
- https://wiki.python.org/moin/PythonSpeed/PerformanceTips
- https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
3.在Python中创建目录
搜索关键字:
http://search.aol.com/aol/search?q=Python+%E5%88%9B%E5%BB%BA%E7%9B%AE%E5%BD%95
参考方法:
import os, errno def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 (except OSError, exc: for Python <2.5) if exc.errno == errno.EEXIST and os.path.isdir(path): pass else raise
参考链接:
- http://bookshadow.com/weblog/2014/10/02/python-mkdir-p/
- http://www.cnblogs.com/zhoujie/archive/2013/04/10/python7.html
4.在Python中删除dict中的某个元素
结论:
del dict['item_name'] 或 dict.pop("key", None)
参考链接:
- http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary
- http://stackoverflow.com/questions/11277432/how-to-remove-a-key-from-dictionary
- http://docs.python.org/reference/simple_stmts.html#grammar-token-del_stmt
5.获取Python中某个对象的大小以及占用空间大小
搜索关键字:
http://search.aol.com/aol/search?q=python+get+dict+size
=
There’s:
>>> import sys
>>> sys.getsizeof([1,2, 3])
96
>>> a = []
>>> sys.getsizeof(a)
72
>>> a = [1]
>>> sys.getsizeof(a)
80
But I wouldn’t say it’s that reliable, as Python has overhead for each object, and there are objects that contain nothing but references to other objects, so it’s not quite the same as in C and other languages.
Have a read of the docs on sys.getsizeof and go from there I guess.
=
参考链接:
6.用Python获取CPU、内存的使用情况
搜索关键字:
http://search.aol.com/aol/search?q=linux+get+a+running+python+script+mem+detail
结论:
推荐使用psutil模块