writing idiomatic python 读书笔记(1)

近来发现自己写的代码和公司的前辈们的代码差距很大,自己写的东西被他们修改后才能看难过。所以好好学一下这本书了。写点东西记录一下
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!')







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值