近来发现自己写的代码和公司的前辈们的代码差距很大,自己写的东西被他们修改后才能看
。所以好好学一下这本书了。写点东西记录一下
![难过](http://static.blog.csdn.net/xheditor/xheditor_emot/default/sad.gif)
if:
(1)当写一个if 和and结合的语句时:
不应:
if x <=y and y <= z:
应该:
if x <= y <=z:
语言简介也提升了代码性能。
(2)很多人为了代码的简短在if中忽略缩进。这是不应该的:
if name: print (name) # 不是一个好的代码习惯
if name:
print (name)
保留python代码风格才是要做的。
(3)尽量减少不必要的变量使用,使用迭代器可以减少不必要的变量重复
我这样的初学者经常会这样使用代码:
is_name = False
name = 'tom'
if name == 'tom' or name =='dick' or name == 'harry': # 这样写的人很少吧
is_name = True
简短有效率的方法:
name = 'tom'
is_name = name in ('tom','dick','harry') # 额如果是我应该想不到这么好的方法
(4) 避免直接比较True False 和 None
例子:
if foo == True:
这个很明显 应该 : if foo: #简短
(5)使用if和else作为短三元操作符
harmful:
foo = True
value = 0
if foo:
value = 1
print (value)
#以前我不觉的这样写有什么问题,但是python不是这样用的
idiomatic:
foo = True
value = 1 if foo else 0 #a short ternary operator
print (value)
For loops
(1)在循环中使用枚举函数而不是创建一个“索引”变量
很多和我一样来自C的小伙伴或者c++。。写出的代码必然是:
my_cotainer = ['a','b','c']
index = 0
for element in my_containter:
print ('{} {}'.format(index,element))
index +=1
好的代码:
my_cotainer = ['a','b','c']
for index , element in enumerate(my_containter): #内置函数还是比较好用的
print ('{} {}'.format(index,element))
(2)使用关键字来遍历一个iterable
这个应该初学者也是会的
for i in list:
(3)for循环中使用else
一个不被大家所熟知的关于Python的for循环的事实是,它可以包括一个else子句。
要是for没有执行就执行else子句:
Harmful:
for user in get_all_users():
has_malformed_email_address = False
print('Checking {}'.format(user))
for email_address in user.get_all_email_addresses():
if email_is_malformed(email_address):
has_malformed_email_address = True
print('Has a malformed email address!')
break
if not has_malformed_email_address:
print('All email addresses are valid!')
Idiomatic:
for user in get_all_users():
print('Checking {}'.format(user))
for email_address in user.get_all_email_addresses():
if email_is_malformed(email_address):
print('Has a malformed email address!')
break
else:
print('All email addresses are valid!')