大爱

Pythonic释义及示例

2014-09-16

1.什么是Pythonic

简单说来,Pythonic就是简单、优美、清晰,不要过分强调技巧,尽量使用 Python 已经提供的功能以及符合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
$import this


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!

总结而言:

美胜丑,显胜隐,简胜杂,杂胜乱,平胜陡,疏胜密。

找到简单问题的一个方法,最好是唯一的方法(正确的解决之道)。

难以解释的实现,源自不好的主意;如有非常棒的主意,它的实现肯定易于解释。

2. pythonic示例:

2.1 列表解析(List Comprehension)

1
2
[expr for iter_var in iterable]
[expr for iter_var in iterable if cond_expr]

如:

1
2
3
4
N=[x*2 for x in range(10) if x>5]
print N

>>>[12, 14, 16, 18]

2.2 生成器表达式(Generator Expression)

1
2
(expr for iter_var in iterable)
(expr for iter_var in iterable if cond_expr)

如:

1
2
3
4
5
6
N=(x*2 for x in range(10) if x>5)
print N
print list(N)

>>> <generator object <genexpr> at 0x024DD300>
[12, 14, 16, 18]

Generator类似于List Comprehension,但Generator避免了生成整个列表,它返回的是一个generator object(生成器表达式),并使用了按需调用的“惰性计算”(lazy evaluation),只有在检索时才被赋值(evaluated),所以在列表比较长的情况下改善了性能及内存占用。

2.3 使用.format代替%

1
2
3
4
name = 'Joo'
age = 25
print('%s is %s years old. '%(name, age))
print('{0} is {1} years old. '.format(name, age))

2.4 字符串拼接

1
2
list1=('how','are','you')
print ' '.join(list1)

2.5 None判断

判断一个变量是否为空的时候,应该总是用is或者is not,而不要使用=

2.6 对象类型判断

对象类型的比较应该始终用isinstance()代替直接比较类型,如使用if isinstance(obj, int)代替if type(obj) is type(1)

2.7 字符串前后缀判断

在检查前缀或后缀时,用startswith()和endswith()代替对字符串进行切片,如使用if foo.startswith(‘bar’)替代 if foo[:3] == ‘bar’

2.8 变量值交换

使用a,b = b, a代替t=a; a=b; b=t

2.9 判断dict中是否有key

使用dict.has_key(key)代替key in dict

2.10 zip

使用zip将2个有对应关系的list构造一个dict

1
2
3
name=['Tom','Jim']
age=[23,40]
print dict(zip(name,age))

2.11 使用set去掉list中重复数据

1
list(set(oldlist))

2.12 读文件操作,使用with

1
2
3
with open('a.txt','r') as f:
for line in f:
print line

2.13 输出数组的index和值

1
2
3
list = ['a','b','c']
for index, value in enumerate(list):
print index,value

2.14 实现a?b:c

1
return_value = True if a else False
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章