更加pythonic的写法

我会陆陆续续的做些笔记,其实有很多不错的技巧,但我只记录特别特别眼前一亮的。

 

1.交换变量

a,b=b,a

 

2.for...else...的else部分用来处理没有从for循环中断的情况。有了它,我们不用设置状态变量来检查是否for循环有break出来,简单方便。

改进前:

find = False
for x in xrange(1,5):
    if x == 5:
        find = True
        print 'find 5'
        break
if not find:
    print 'can not find 5!'
#can not find 5!

 

改进后:

for x in xrange(1,5):
    if x == 5:
        print 'find 5'
        break
else:
    print 'can not find 5!'
#can not find 5!   

转载于:https://www.cnblogs.com/encode/p/5231475.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值