Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。
要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,Github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里小明收集了一些常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。
01. 变量交换
Bad
tmp = a a = b b = tmp
Pythonic
a,b = b,a
02. 列表推导
Bad
my_list = [] for i in range(10): my_list.append(i*2)
Pythonic
my_list = [i*2 for i in range(10)]
03. 单行表达式
虽然列表推导式由于其简洁性及表达性,被广受推崇。
但是有许多可以写成单行的表达式,并不是好的做法。
Bad
print 'one'; print 'two' if x == 1: print 'one' if <complex comparison> and <other complex comparison>: # do something
Pythonic
print 'one' print 'two' if x == 1: print 'one' cond1 = <complex comparison> cond2 = <other complex comparison> if cond1 and cond2: # do something
04. 带索引遍历
Bad
for i in range(len(my_list)): print(i, "-->", my_list[i])
Pythonic
for i,item in enumerate(my_list): print(i, "-->",item)
05. 序列解包
Pythonic
a, *rest = [1, 2, 3] # a = 1, rest = [2, 3] a, *middle, c = [1, 2, 3, 4] # a = 1, middle = [2, 3], c = 4
06. 字符串拼接
Bad
letters = ['s', 'p', 'a', 'm'] s="" for let in letters: s += let
Pythonic
letters = ['s', 'p', 'a', 'm'] word = ''.join(letters)
07. 真假判断
Bad
if attr == True: print 'True!' if attr == None: print 'attr is None!'
Pythonic
if attr: print 'attr is truthy!' if not attr: print 'attr is falsey!' if attr is None: print 'attr is None!'
08. 访问字典元素
Bad
d = {'hello': 'world'} if d.has_key('hello'): print d['hello'] # prints 'world' else: print 'default_value'
Pythonic
d = {'hello': 'world'} print d.get('hello', 'default_value') # prints 'world' print d.get('thingy', 'default_value') # prints 'default_value' # Or: if 'hello' in d: print d['hello']
09. 操作列表
Bad
a = [3, 4, 5] b = [] for i in a: if i > 4: b.append(i)
Pythonic
a = [3, 4, 5] b = [i for i in a if i > 4] # Or: b = filter(lambda x: x > 4, a)
Bad
a = [3, 4, 5] for i in range(len(a)): a[i] += 3
Pythonic
a = [3, 4, 5] a = [i + 3 for i in a] # Or: a = map(lambda i: i + 3, a)
10. 文件读取
Bad
f = open('file.txt') a = f.read() print a f.close()
Pythonic
with open('file.txt') as f: for line in f: print line
11. 代码续行
Bad
my_very_big_string = """For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say “I'm going to sleep.”""" from some.deep.module.inside.a.module import a_nice_function, another_nice_function, yet_another_nice_function
Pythonic
my_very_big_string = ( "For a long time I used to go to bed early. Sometimes, " "when I had put out my candle, my eyes would close so quickly " "that I had not even time to say “I'm going to sleep.”" ) from some.deep.module.inside.a.module import ( a_nice_function, another_nice_function, yet_another_nice_function)
12. 显式代码
Bad
def make_complex(*args): x, y = args return dict(**locals())
Pythonic
def make_complex(x, y): return {'x': x, 'y': y}
13. 使用占位符
Pythonic
filename = 'foobar.txt' basename, _, ext = filename.rpartition('.')
14. 链式比较
Bad
if age > 18 and age < 60: print("young man")
Pythonic
if 18 < age < 60: print("young man")
理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False
> False == False == True False
15. 三目运算
这个保留意见。随使用习惯就好。
Bad
if a > 2: b = 2 else: b = 1 #b = 2
Pythonic
a = 3 b = 2 if a > 2 else 1 #b = 2
参考文档
http://docs.python-guide.org/en/latest/writing/style/
https://foofish.net/idiomatic_part2.html
Pythonic
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 《暗喻幻想》顺风耳作用介绍
- 崔健1985-梦中的倾诉[再版][WAV+CUE]
- 黄子馨《追星Xin的恋人们2》HQ头版限量编号[WAV+CUE]
- 孟庭苇《情人的眼泪》开盘母带[低速原抓WAV+CUE]
- 孙露《谁为我停留HQCD》[低速原抓WAV+CUE][1.1G]
- 孙悦《时光音乐会》纯银CD[低速原抓WAV+CUE][1.1G]
- 任然《渐晚》[FLAC/分轨][72.32MB]
- 英雄联盟新英雄安蓓萨上线了吗 新英雄安蓓萨技能介绍
- 魔兽世界奥杜尔竞速赛什么时候开启 奥杜尔竞速赛开启时间介绍
- 无畏契约CGRS准星代码多少 CGRS准星代码分享一览
- 张靓颖.2012-倾听【少城时代】【WAV+CUE】
- 游鸿明.1999-五月的雪【大宇国际】【WAV+CUE】
- 曹方.2005-遇见我【钛友文化】【WAV+CUE】
- Unity6引擎上线:稳定性提升、CPU性能最高提升4倍
- 人皇Sky今日举行婚礼!电竞传奇步入新篇章