让你的 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,337评论 19 139
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 9,709评论 0 16
  • 一、python 变量和数据类型 1.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序...
    绩重KF阅读 5,782评论 0 1
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,441评论 11 349
  • 咳咳,首先来介绍一下我自己吧。 我挺蠢的。为什么这么说?举个例子,这本笔记完全是写给我自己看得,但出于某种愚蠢的原...
    三千叶渔舟阅读 1,670评论 0 0