如何优雅高效地使用Python——这些Python技巧你必须学会!

前言

目前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:优雅高效的写法

多变量赋值

当你想要初始化多个变量的时候:

  1. Bad
x = []
y = []
z = []
  1. Better
x, y, z = [], [], []

这样做的话代码更加简洁,同时可读性更高

变量交换

  1. Bad
# edchange x and y
t = x
x = y
y = t
  1. Better
# edchange x and y
x, y = y, x

这样做的话不止代码简洁,让人一眼就能看出是要交换变量,同时也能免去考虑中间变量赋值的先后顺序,并且后者的效率更是高于前者。

格式化字符串

如果你想要格式化输出一串字符串,你会怎么做?

  1. 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'
  1. 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'
  1. 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)

当你想同时访问两个列表的时候,你的做法是?

  1. 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

  1. 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)

当你需要将一个二元组序列拆成两列,你会怎么做?

  1. Bad
Data = [('James', 18), ('Tim', 19), ('Katty', 20)]
names, ages = [], []
for name, age in Data:
    names.append(name)
    ages.append(age)
  1. Better
Data = [('James', 18), ('Tim', 19), ('Katty', 20)]
names = [data[0] for data in Data]
ages = [data[1] for data in Data]
  1. Best
Data = [('James', 18), ('Tim', 19), ('Katty', 20)]
names, ages = zip(*Data)

zip()zip(*)是一对互逆操作,不过需要注意,zip()zip(*)在Python 3返回的都是迭代器,然后zip(*)通过解包返回多个元组。

条件表达式

  1. Bad
if x<y:
    small=x
else:
    small=y
  1. Better
small = x if x<y else y

后者不仅表达意思更加明了,同时代码量也少了好几行。

if结构简化

如果你需要检查几个数值时:

  1. Bad
if x==1 or x==2 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值