python惯用方法整理(Pythonic 1)
2016-09-22 00:00
155 查看
摘要: 本文是从官方文档、stackoverflow和工作中收集、摘录和整理出来的一些python惯用方法,罗列在此,be more pythonic。
用:
舍弃:
For Python 3.3 and 3.4 use:
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
注:Without the main sentinel, the code would be executed even if the script was imported as a module.
设置递归深度,默认递归深度1000
is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:
so, no wonder they're not the same, right?
In other words: 'is' is the id(a) == id(b)
None
False
zero of any numeric type, for example, 0, 0.0, 0j.
为0的数字类型,如整型、浮点型、复数。
any empty sequence, for example, '', (), [].
空序列,如:'',(),[]。
any empty mapping, for example, {}.
空映射,如:{}。
或者
和[::-1]相比,上面方法没有创建新的list对象,仅生成了一个迭代器对象
EAFP VS LBYL
"Easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL)用:
try: doStuff(a.property) except AttributeError: otherStuff()
舍弃:
if hasattr(a, 'property'): doStuff(a.property) else: otherStuff()
检查python运行版本
>>> import sys >>> print(sys.version) 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)]
检查python使用的cpu数量
>>> import multiprocessing >>> multiprocessing.cpu_count() ...
不运行脚本检查语法
python -m py_compile script.py
从指定路径加载module
For Python 3.5+ use:import importlib.util spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) foo.MyClass()
For Python 3.3 and 3.4 use:
from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() foo.MyClass()
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass()
main的写法
if __name__ == "__main__": pass
__name__ == "__main__" and main()
注:Without the main sentinel, the code would be executed even if the script was imported as a module.
递归
按层级输出一个文件夹下的文件结构import os _PATH = r"F:\MyDjango\mydjango\mysite\static" def showdir(path, n): print((n-1) * "----" + path.replace(_PATH + "\\", "")) for d in os.listdir(path): subpath = os.path.join(path, d) if os.path.isdir(subpath): showdir(subpath, n + 1) else: print(n * "----" + subpath.replace(_PATH + "\\", "")) if __name__ == "__main__": showdir(_PATH, 1)
设置递归深度,默认递归深度1000
import sys print(sys.getrecursionlimit()) sys.setrecursionlimit(1234) print(sys.getrecursionlimit())
运算符:is VS ==
stackoverflow原文is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:
>>> a = 'pub' >>> b = ''.join(['p', 'u', 'b']) >>> a == b True >>> a is b False
so, no wonder they're not the same, right?
In other words: 'is' is the id(a) == id(b)
True Or False
以下都是False(参见py说明文档)None
False
zero of any numeric type, for example, 0, 0.0, 0j.
为0的数字类型,如整型、浮点型、复数。
any empty sequence, for example, '', (), [].
空序列,如:'',(),[]。
any empty mapping, for example, {}.
空映射,如:{}。
>>> if not (None or False or 0 or 0.0 or 0j or '' or () or [] or {}): ... print('False') False
list的index
从字符串看 list 的 index,(以下来自Python帮助文档)/******* +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 ************************/
简化创建list/tuple
# list or tuple [ o.dosomething for o in objects if True ]
或者
[ dosomething if x... else ... for x in Xs]
倒序list
>>> a = ["foo", "bar", "baz"] >>> for i in reversed(a): ... print i >>> reversed(a) <list_reverseiterator object at 0x...>
和[::-1]相比,上面方法没有创建新的list对象,仅生成了一个迭代器对象
>>>for i in a[::-1]: ... pass >>> mylist[::-1] >>> mylist[-2::-1]
相关文章推荐
- python惯用方法整理(Pythonic 2)
- python惯用方法整理(Pythonic 3)
- python中字符串内置方法整理
- python序列整理出来的方法
- scrapy一些非常实用资料整理,与其他mongdb、django、redis、solr、tor结合使用以及用Python脚本调用等等方法
- 收藏整理的一些Python常用方法和技巧
- 收藏整理的一些Python常用方法和技巧
- python exec, eval 方法整理
- Python中selenium实现文件上传所有方法整理总结
- Python3 爬虫编写报错及解决方法整理
- [整理] python的正则表达式re模块的常用方法
- python3基础之整数常用的方法整理
- 通过Python的内置字符串处理函数来处理字符串的方法和整理
- Pythonic 的代码编写方法
- Python3 方法整理
- python中读写文件及中文编码处理方法【整理】
- 整理Python最基本的操作字典的方法
- python数据类型list方法整理
- Python 字符串方法,经过表格整理,清楚明了(转)
- 自己编程中遇到的Python错误和解决方法汇总整理