让你的 Python 代码更简洁易懂

作者: 日三省 | 来源:发表于2016-07-04 16:14 被阅读391次
1. 遍历输出数组
array = ['a', 'b', 'c', 'd']

# The bad way
i = 0
for arr in array:
    print i, arr
    i += 1

# The better way
for i, arr in enumerate(array):
    print i, arr

# Run and output
>>> 
0 a
1 b
2 c
3 d
0 a
1 b
2 c
3 d

2. 交叉遍历两个数组
x_list = [1, 2, 3]
y_list = [4, 5, 6]

# The bad way
for i in range(len(x_list)):
    x = x_list[i]
    y = y_list[i]
    print x, y

# The better way
for x, y in zip(x_list, y_list):
    print x, y

# Run and output
>>> 
1 4
2 5
3 6
1 4
2 5
3 6

3. 交换两个变量的值
x = 1
y = 2
print x, y

# The bad way
temp = y
y = x
x = temp
print x, y

x = 1
y = 2
print x, y

# The better way
x, y = y, x
print x, y

# Run and output
>>> 
1 2
2 1
1 2
2 1

4. Dict 用 get 取某个 key 值
dic = {
    'Name'    :'John',
    'City'    :'Shanghai'
}

# The bad way
city = ''
if dic.has_key('City'):
    city = dic['City']
else:
    city = 'Unknown'
print city

# The better way
city = dic.get('City', 'Unknown')
print city

# Test the no-key condition 
dic = {
    'Name'    :'John',
    'Sex'     :'Male'
}

city = dic.get('City', 'Unknown')
print city

# Run and output
>>> 
Shanghai
Shanghai
Unknown

5. 利用 for 循环的 else
find = 'b'
array = ['b', 'b', 'c', 'd', 'e']

# The bad way
found = False
for arr in array:
    if find == arr:
        print 'Found!'
        found = True
        break
if not found:
    print 'Not found!'

# The better way
for arr in array:
    if find == arr:
        print 'Found!'
        break
else: # This else means no-break occurred
    print 'Not found!'

# Test the not-found condition

find = 'f'
for arr in array:
    if find == arr:
        print 'Found!'
        break
else: # This else means no-break occurred
    print 'Not found!'

# Run and output
>>> 
Found!
Found!
Not found!

6. 读取文件
# The bad way
f = open('xxx.txt')
text = f.read()
for line in text.split('\n'):
    print line
f.close()

# The better way
with open('xxx.txt') as f:
    for line in f:
        print line

7. 异常的 else
print 'Converting...'
print int('1')
print 'Done'

# The bad way
print 'Converting...'
try:
    print int('x')
except:
    print 'Conversion failed.'
print 'Done'

# The better way
print 'Converting...'
try:
    print int('x')
except:
    print 'Conversion failed.'
else: # This else means no-except occurred
    print 'Conversion successful.'
finally:
    print 'Done'

# Run and output
>>>
Converting...
1
Done
Converting...
Conversion failed.
Done
Converting...
Conversion failed.
Done

相关文章

  • 让你的 Python 代码更简洁易懂

    1. 遍历输出数组 2. 交叉遍历两个数组 3. 交换两个变量的值 4. Dict 用 get 取某个 key 值...

  • 让你的表达更简洁易懂

    完成文章构思之后,写出来的观点很可能互相之间没有太多关联,又或者是没有进行恰当的分类显得有些混乱。 这时候就需要用...

  • java爬虫与python爬虫谁更强?

    java爬虫与python爬虫的对比: python做爬虫语法更简单,代码更简洁。java的语法比python严格...

  • 125. 验证回文串

    题外话 简洁易懂的代码是好代码. 注意事项 python 字符判断是何种类型的写法 条件的处理, 使用 conti...

  • Fly Jquery ( you might not need

    jQuery 作为一款优秀的JavaScript框架,使用 JQuery能够让你写出更加简洁易懂的代码,提高开发效...

  • javascript “||” 和 “&&” 小技巧

    javascript中有很多小技巧,可以让代码变得简洁、易读、易懂。 我们今天先来看看 “||” 和 “&&” 小...

  • Lombok让代码更简洁

    Lombok 简介 Lombok项目通过添加“处理程序”,使java成为一种更为简单的语言。 简单来说,比如我们新...

  • 让 JS 代码更简洁

    文章结尾我会附上视频地址,有自己想法的可以留言交流,谢谢? 1. 输出对象快速查看 低效输出 console.lo...

  • Anko for Android

    Anko 是一个使开发Android应用更简单更快捷的库,Anko使你的代码简洁易懂, 使开发者不用再在意Andr...

  • 一文搞定Python垃圾回收机制

    python作为一门解释型语言,以代码简洁易懂著称。我们可以直接对名称赋值,而不必声明类型。名称类型的确定、内存空...

网友评论

    本文标题:让你的 Python 代码更简洁易懂

    本文链接:https://www.haomeiwen.com/subject/dwttjttx.html