您的位置:首页 > 编程语言 > Python开发

python惯用方法整理(Pythonic 1)

2016-09-22 00:00 155 查看
摘要: 本文是从官方文档、stackoverflow和工作中收集、摘录和整理出来的一些python惯用方法,罗列在此,be more pythonic。

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: