文章目录
前言
目前Python已经更新到了3.7版本,不必多说,Python 3比Python 2更是多出了许多新的功能。Python是一门友好的语言,其区别于以往C++,Java的特点不仅是代码易于阅读,同时代码也更加优雅简洁,实现同样的功能相对于Python只需要短短几行代码,这给予了开发人员更大的便利,同时也易于初学者学习。本文将介绍Python中一些有趣实用的(代码)功能,希望这些代码能够帮助大家更加轻松优雅地解决一些问题。
注:本博客代码结果均为Python 3.6版本运行结果
Python之禅
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!
Python之禅 by Tim Peters
优美胜于丑陋(Python以编写优美的代码为目标)
明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)
简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)
复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)
扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)
间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)
可读性很重要(优美的代码是可读的)
即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)
不要包容所有错误,除非您确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)
当存在多种可能,不要尝试去猜测
而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)
虽然这并不容易,因为您不是 Python 之父(这里的 Dutch 是指 Guido )
做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)
如果您无法向人描述您的方案,那肯定不是一个好方案;反之亦然(方案测评标准)
命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)
Python:优雅高效的写法
多变量赋值
当你想要初始化多个变量的时候:
- Bad
x = []
y = []
z = []
- Better
x, y, z = [], [], []
这样做的话代码更加简洁,同时可读性更高
变量交换
- Bad
# edchange x and y
t = x
x = y
y = t
- Better
# edchange x and y
x, y = y, x
这样做的话不止代码简洁,让人一眼就能看出是要交换变量,同时也能免去考虑中间变量赋值的先后顺序,并且后者的效率更是高于前者。
格式化字符串
如果你想要格式化输出一串字符串,你会怎么做?
- Bad
name = "James"
country = "USA"
string = "My name is %s, from %s, I love %s" % (name, country, country)
>>> string
'My name is James, from USA, I love USA'
- Better
name = "James"
country = "USA"
string = "My name is {}, from {}, I love {}".format(name, country, country)
>>> string
'My name is James, from USA, I love USA'
- Best
name = "James"
country = "USA"
string = "My name is {name}, from {country}, I love {country}".format(name=name, country=country)
'My name is James, from USA, I love USA'
# or you can simplipy it by using f-strings
name = "James"
country = "USA"
string = f"My name is {name}, from {country}, I love {country}"
>>> string
'My name is James, from USA, I love USA'
使用format
函数比使用%s
可读性更高,同时也更易于控制输出格式。
序列并包(pack)
当你想同时访问两个列表的时候,你的做法是?
- Bad
names = ['James', 'Tim', 'Katty']
ages = [18, 19, 20]
for i in range(len(names)):
print("name:", names[i],"age:", ages[i])
name: James age: 18
name: Tim age: 19
name: Katty age: 20
- Better
names = ['James', 'Tim', 'Katty']
ages = [18, 19, 20]
for name, age in zip(names,ages):
print("name:", name,"age:", age)
name: James age: 18
name: Tim age: 19
name: Katty age: 20
后者的方法不仅一目了然,同时遍历元素的行为比遍历下标的行为更加高效!
序列解包(unpack)
当你需要将一个二元组序列拆成两列,你会怎么做?
- Bad
Data = [('James', 18), ('Tim', 19), ('Katty', 20)]
names, ages = [], []
for name, age in Data:
names.append(name)
ages.append(age)
- Better
Data = [('James', 18), ('Tim', 19), ('Katty', 20)]
names = [data[0] for data in Data]
ages = [data[1] for data in Data]
- Best
Data = [('James', 18), ('Tim', 19), ('Katty', 20)]
names, ages = zip(*Data)
zip()
和zip(*)
是一对互逆操作,不过需要注意,zip()
和zip(*)
在Python 3返回的都是迭代器,然后zip(*)
通过解包返回多个元组。
条件表达式
- Bad
if x<y:
small=x
else:
small=y
- Better
small = x if x<y else y
后者不仅表达意思更加明了,同时代码量也少了好几行。
if结构简化
如果你需要检查几个数值时:
- Bad
if x==1 or x==2 or x==3 or x==4:
print("x =1 or 2 or 3 or 4")
- Better
if x in (1,2,3,4):
print("x =1 or 2 or 3 or 4")
if链式条件表达式
- Bad
if x>0 and x<10:
print("0<x<10"