Python之禅

this模块是一首关于python设计哲学的诗,import this后就会输出诗的内容。也叫《Python之禅》。

import this执行后的结果如下。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
``

翻译成中文如下

python The Zen of Python, by Tim Peters

Python之禅 Tim Peters

Beautiful is better than ugly.

优美胜于丑陋(Python以编写优美的代码为目标)

Explicit is better than implicit.

明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)

Simple is better than complex.

简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)

Complex is better than complicated.

复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)

Flat is better than nested.

扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)

Sparse is better than dense.

间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)

Readability counts.

可读性很重要(优美的代码是可读的)

Special cases aren’t special enough to break the rules. Although practicality beats purity.

即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)

Errors should never pass silently. Unless explicitly silenced.

不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写except:pass风格的代码)

In the face of ambiguity, refuse the temptation to guess.

当存在多种可能,不要尝试去猜测

There should be one– and preferably only one –obvious way to do it.

而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)

Although that way may not be obvious at first unless you’re Dutch.

虽然这并不容易,因为你不是 Python 之父(这里的Dutch是指Guido)

Now is better than never. Although never is often better than right now.

做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)

If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea.

如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然(方案测评标准)

Namespaces are one honking great idea – let’s do more of those!

1
2
3
4
5
Pythonic比较难定义,你可以理解成符合python设计哲学的就是Pythonic。

## pythonic简洁写法

### 检查是否为空

python s = “hello” L = [‘a’, ‘b’, ‘c’] t = (‘a’, ‘b’, ‘c’) set = {‘a’, ‘b’, ‘c’} d = {‘a’:1, ‘b’:2, ‘c’:3}

#推荐 if s: print(“字符串s非空”) if L: print(“列表L非空”) if t: print(“元组t非空”) if set: print(“集合set非空”) if d: print(“字典d非空”) #或者 if not s: print(“字符串s空”) else print(“字符串s非空”)

if not L: print(“列表L空”) else print(“列表L非空”)

if not t: print(“元组t空”) else print(“元组t非空”)

if not set: print(“集合set空”) else print(“集合set非空”)

if not d: print(“字典d空”) else print(“字典d非空”)

#不推荐 if len(s) != 0: print(“字符串s非空”) if len(L) != 0: print(“列表L非空”) if len(t) != 0: print(“元组t非空”) if len(set) != 0: print(“集合set非空”) if len(d) != 0: print(“字典d非空”)

#不推荐 if s != “”: print(“字符串s非空”) if L != []: print(“列表L非空”) if t != (): print(“元组t非空”) if d != {}: print(“字典d非空”)

1
### 真值测试

python s = “hello” L = [‘a’, ‘b’, ‘c’] t = (‘a’, ‘b’, ‘c’) set = {‘a’, ‘b’, ‘c’} d = {‘a’:1, ‘b’:2, ‘c’:3}

#推荐 if s and L and t and set and d: print(‘All True!’) #输出 All True!

#不推荐 if s != “ and len(L) > 0 and len(t) >0 and len(set) > 0 and d != {}: print(‘All True!’) #输出 All True!

1
### 字符串翻转

python #推荐 def reverse_str(s): return s[::-1]

#不推荐 def reverse_str(s): t = “ for x in range(len(s)-1,-1,-1): t += s[x] return t

1
### 字符串列表的连接

python #推荐 strList = [“Python”, “is”, “good”]
res = ‘ ‘.join(strList) #Python is good

#不推荐 res = “ for s in strList: res += s + ‘ ‘

1
### 链式比较

python a = 3 b = 1

#推荐 result = 1 <= b <= a < 10

#不推荐 result = b >= 1 and b <= a and a < 10

1
### 列表求和,最大值,最小值,乘积

python #推荐 numList = [1,2,3,4,5] sum = sum(numList) #sum = 15 maxNum = max(numList) #maxNum = 5 minNum = min(numList) #minNum = 1 from operator import mul prod = reduce(mul, numList, 1) #prod = 120 默认值传1以防空列表报错

#不推荐 sum = 0 maxNum = -float(‘inf’) minNum = float(‘inf’) prod = 1 for num in numList: if num > maxNum: maxNum = num if num < minNum: minNum = num sum += num prod *= num

sum = 15 maxNum = 5 minNum = 1 prod = 120

1
### 列表推导式

python #推荐 l = [x*x for x in range(10) if x%3== 0] #结果 [0, 9, 36, 81]

python #不推荐 l = [] for x in range(10): if x % 3 == 0: l.append(x*x) #结果 [0, 9, 36, 81]

1
### 字典的默认值

python #推荐 dic = {‘name’:‘Tim’, ‘age’:23}
dic[‘workage’] = dic.get(‘workage’,0) + 1 #结果 {‘age’: 23, ‘workage’: 1, ‘name’: ‘Tim’}

#不推荐 if ‘workage’ in dic: dic[‘workage’] += 1 else: dic[‘workage’] = 1 #结果 {‘age’: 23, ‘workage’: 1, ‘name’: ‘Tim’}

1
### 使用zip创建键值对

python #推荐 keys = [‘Name’, ‘Sex’, ‘Age’] values = [‘Tim’, ‘Male’, 23] dic = dict(zip(keys, values)) #结果{‘Age’: 23, ‘Name’: ‘Tim’, ‘Sex’: ‘Male’}

python #不推荐 dic = {} for i,e in enumerate(keys): dic[e] = values[i] #结果{‘Age’: 23, ‘Name’: ‘Tim’, ‘Sex’: ‘Male’}

1
### 使用 in/not in 检查key是否存在于字典

python #推荐 if key in dictionary: print(True) else print False

python #不推荐 dictionary={} keys=dictionary.keys() for k in keys if key==k print(True) break

1
### 使用 setdefault()初始化字典键值

python #推荐 dictionary={} dictionary.setdefault(“key”, []).append(“list_item”)

1
字典调用setdefault方法时,首先检查key是否存在,如果存在该方法什么也不做,如果不存在setdefault就会创建该key,并把第二个参数[]作为key对应的值。

python #不推荐 dictionary={} if “key” not in dictionary: dictionary[“key”] = [] dictionary[“key”].append(“list_item”)

1
2
3
4
5
尽管这段代码没有任何逻辑错误,但是我们可以使用setdefault来实现更Pyhonic的写法:

### 使用defaultdict()初始化字典

初始化一个字典时,如果初始情况下希望所有key对应的值都是某个默认的初始值,比如有一批用户的信用积分都初始为100,现在想给a用户增加10分

python #推荐 from collections import defaultdict d = defaultdict(lambda: 100) d[‘a’] += 10

python #不推荐 d = {} if ‘a’ not in d: d[‘a’] = 100 d[‘a’] += 10]

1
2
3
### 使用iteritems()迭代大数据

迭代大数据字典时,如果是使用items()方法,那么在迭代之前,迭代器迭代前需要把数据完整地加载到内存,这种方式不仅处理非常慢而且浪费内存.

python #不推荐 d = {i: i * 2 for i in xrange(10000000)} for key, value in d.items(): print(“{0} = {1}”.format(key, value))

1
而使用 iteritem()方法替换items() ,最终实现的效果一样,但是消耗的内存降50%,为什么差距那么大呢?因为items()返回的是一个list,list在迭代的时候会预先把所有的元素加载到内存,而iteritem() 返回的一个迭代器(iterators),迭代器在迭代的时候,迭代元素逐个的生成.

python #推荐 d = {i: i * 2 for i in xrange(10000000)} for key, value in d.iteritem(): print(“{0} = {1}”.format(key, value)) ```


转载请注明本网址。