让你的 Python 代码更简洁易懂

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

    原文作者:日三省
    原文地址: https://www.jianshu.com/p/1d73639c61e7
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞