更加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