今天看到一篇文章,感觉非常棒,就在此记录下来,和大家一起共勉。
备注:本博客参看微信公众号Python之禅
a = 1
b = 2
tmp = a
a = b
b = tmp
print(a, b)
pythonic:
a,b = b,a
2:循环遍历列表元素
for i in [1,2,3,4,5,6,7]:
print (i)
# 或者
for i range(7):
print (i)
pythonic:
for i xrange(7):
print (i)
xrange返回的是生成器对象,生成器比列表更加节省内存,不过需要注意的是xrange是python2的写法,python3只有range方法
3:带有索引位置的集合遍历
遍历集合时如果需要使用到集合的索引位置,直接对集合迭代是没有索引信息的,普通的方式:
books = ["java","python","nodeJs","React"]
for i in range(len(books)):
print(i , books[i])
pythonic:
for i, book in enumerate(books):
print(i, book)
4: 字符串的拼接
拼接字符串是普通的方式是使用+号
names = ["jack","tom","jerry","smith"]
s = names[0]
for name in names[1:]:
s += "," + name
print(s)
pythonic:
print(",".join(names))
join是一种更加高效的字符串拼接方式,使用+号操作时,每执行一次+操作都会导致在内存中产生一个新的字符串对象,从而造成无畏的内存浪费,而使用join整个过程中只产生一个字符串对象
5:打开关闭文件
f = open("test.py")
try:
data = f.read()
except IOError:
pass
finally:
f.close()
pythonic:
with open("test.py") as f:
data = f.read() # 系统在执行完毕后会自动关闭文件对象
6:列表推导式
result = []
for i in range(10):
result.append(i*2)
pythonic:
result = [i*2 for i in range(10)]
7: 合理使用列表
列表对象(list)是一个查询效率高于更新操作的数据结构,比如删除一个元素或插入一个元素时执行效率非常低,因为还要对剩下的元素进行移动
names = ["jack","tom","jerry","smith"]
names.pop(0)
names.insert(0,"mark")
pythonic:
from collections import deque # deque是一个双向队列的数据结构,删除元素和插入元素都很快
names = deque(["jack","tom","jerry","smith"])
names.popleft()
names.appendleft("mark")
print(names) # deque(['mark', 'tom', 'jerry', 'smith'])
8:序列解包
person = ["jack","male",23,"python.email.com"]
name = person[0]
gender = person[1]
age = person[2]
email = person[3]
print(name, gender, age, email)
pythonic:
name, gender, age, email = person
print(name, gender, age, email)
看到了上面的两种不同风格的编码,内心是不是有点小激动,这也是python的强大之一,语法相当的简洁,一点一步拖泥带水,还有很多的pythonic写法,今天就暂时写到这里。未完待续……
Tipes:非常感谢Python之禅作者的分享,在此附上原文链接原文链接