一些优雅的 Python 编码技巧
1、交换赋值
# 不推荐写法
c = a
a = b
b = c
# 推荐写法
a,b = b,a
2、in
# 不推荐写法
if a == '1' or a == '2' or a == '3':
# 推荐写法
if a in ['1','2','3']:
3、列表中元素进行字符串拼接操作
# 不推荐写法
city = ['shanghai','beijing','shenzheng']
new = ''
for item in city:
new += item
# 推荐写法(好处:不占用内存)
city = ['shanghai','beijing','shenzheng']
new = ''.join(city)
4、遍历列表及其索引
# 不推荐写法
items = 'a b c'.split()
## 方法1
i = 0
for item in items:
print(i,item)
i += 1
## 方法2
for i in range(len(items)):
print(i,item[i])
# 推荐写法
items = 'a b c'.split()
for i,item in enumerate(items):
print(i,item)
5、循环嵌套
# 不推荐写法
for x in list1:
for y in list2:
for z in list3:
......
# 推荐写法
from itertools import product
for x,y,z in product(list1,list2,list3):
......
6、with 打开文件
# 不推荐写法
f = open('test.txt')
try:
data = f.read()
...
finally:
f.close()
# 推荐写法
with open('test.txt') as f:
date = r.read()
......