15个Pythonic的代码示例(值得收藏)
作者:zx 发布时间:2022-07-27 21:21:19
Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。
要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,Github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里小明收集了一些常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。
01. 变量交换
Bad
tmp = a
a = b
b = tmp
Pythonic
a,b = b,a
02. 列表推导
Bad
my_list = []
for i in range(10):
my_list.append(i*2)
Pythonic
my_list = [i*2 for i in range(10)]
03. 单行表达式
虽然列表推导式由于其简洁性及表达性,被广受推崇。
但是有许多可以写成单行的表达式,并不是好的做法。
Bad
print 'one'; print 'two'
if x == 1: print 'one'
if <complex comparison> and <other complex comparison>:
# do something
Pythonic
print 'one'
print 'two'
if x == 1:
print 'one'
cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
# do something
04. 带索引遍历
Bad
for i in range(len(my_list)):
print(i, "-->", my_list[i])
Pythonic
for i,item in enumerate(my_list):
print(i, "-->",item)
05. 序列解包
Pythonic
a, *rest = [1, 2, 3]
# a = 1, rest = [2, 3]
a, *middle, c = [1, 2, 3, 4]
# a = 1, middle = [2, 3], c = 4
06. 字符串拼接
Bad
letters = ['s', 'p', 'a', 'm']
s=""
for let in letters:
s += let
Pythonic
letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)
07. 真假判断
Bad
if attr == True:
print 'True!'
if attr == None:
print 'attr is None!'
Pythonic
if attr:
print 'attr is truthy!'
if not attr:
print 'attr is falsey!'
if attr is None:
print 'attr is None!'
08. 访问字典元素
Bad
d = {'hello': 'world'}
if d.has_key('hello'):
print d['hello'] # prints 'world'
else:
print 'default_value'
Pythonic
d = {'hello': 'world'}
print d.get('hello', 'default_value') # prints 'world'
print d.get('thingy', 'default_value') # prints 'default_value'
# Or:
if 'hello' in d:
print d['hello']
09. 操作列表
Bad
a = [3, 4, 5]
b = []
for i in a:
if i > 4:
b.append(i)
Pythonic
a = [3, 4, 5]
b = [i for i in a if i > 4]
# Or:
b = filter(lambda x: x > 4, a)
Bad
a = [3, 4, 5]
for i in range(len(a)):
a[i] += 3
Pythonic
a = [3, 4, 5]
a = [i + 3 for i in a]
# Or:
a = map(lambda i: i + 3, a)
10. 文件读取
Bad
f = open('file.txt')
a = f.read()
print a
f.close()
Pythonic
with open('file.txt') as f:
for line in f:
print line
11. 代码续行
Bad
my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
when I had put out my candle, my eyes would close so quickly that I had not even \
time to say “I'm going to sleep.”"""
from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
yet_another_nice_function
Pythonic
my_very_big_string = (
"For a long time I used to go to bed early. Sometimes, "
"when I had put out my candle, my eyes would close so quickly "
"that I had not even time to say “I'm going to sleep.”"
)
from some.deep.module.inside.a.module import (
a_nice_function, another_nice_function, yet_another_nice_function)
12. 显式代码
Bad
def make_complex(*args):
x, y = args
return dict(**locals())
Pythonic
def make_complex(x, y):
return {'x': x, 'y': y}
13. 使用占位符
Pythonic
filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')
14. 链式比较
Bad
if age > 18 and age < 60:
print("young man")
Pythonic
if 18 < age < 60:
print("young man")
理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False
>>> False == False == True
False
15. 三目运算
这个保留意见。随使用习惯就好。
Bad
if a > 2:
b = 2
else:
b = 1
#b = 2
Pythonic
a = 3
b = 2 if a > 2 else 1
#b = 2
参考文档
http://docs.python-guide.org/en/latest/writing/style/
https://foofish.net/idiomatic_part2.html
来源:https://blog.csdn.net/weixin_36338224/article/details/108962337


猜你喜欢
- 1、首先需要在vue-cli项目中配置bootstrap,jquery2、 然后新建vue文件,如index.vue,index.vue内容
- 接触了一下docker和k8s,感觉是非常不错的东西。能够方便的部署线上环境,而且还能够更好的利用机器的资源,感觉是以后的大趋势。最近刚好有
- 修改字符串本身是不可能的,因为字符串是不可变类型,只能是通过某些方法来产生它的副本。再把副本赋值给原字符串,达到类似替换的作用。这里介绍几种
- UI设计图Echarts示例效果前言对于UI给出的设计图,各个气象网站都有类似的效果,实现方式大可归为两种:网格布局+图表框架绘制温度曲线;
- VuePressvuepress是尤大大4月12日发布的一个全新的基于vue的静态网站生成器,实际上就是一个vue的spa应用,内置webp
- 在存储过程中,请问如何判断所指定表的字段的类型?由于表和视图的每一列在SYSCOLUMNS表中都有详细资料,所以,我们只管从中取用来即可,很
- 仿射密码思路:1、加解密公式:2、构造对应字典:3、代码实现构造字典,建立映射关系:# 构造字典,'A' --> 0
- SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它
- Jupyter notebook 更改文件打开的默认路径第一步:修改图标- 找到 Jupyter notebook 桌面图标- 对着 Jup
- 没废话,直接上代码。环境说明:python3.6django2.0.5我们使用redis的作为celery任务队列,有一个合成包可以直接安装
- 目录生活中的例子慢查询如何去优化countlimit最大值最小值min&max生活中的例子我们是否看到过在公司中许多查询语句都是se
- Python读写文件模式 1、r 打开只读文件,该文件必须存在。 2、r+ 打开可读写的文件,该文件必须存在。 3、w 打开只写文件,若文件
- 前言return语句用于退出函数,向调用方返回一个表达式。return在不带参数的情况下(或者没有写return语句),默认返回None。N
- <style> *{position:absolute;} #panel *{border:1px so
- 解决安装Office2003 SP2后不能打开Access的问题手动更改注册表要解决此问题, 手动更改计算机上注册表位置启动 Access
- 0. 简介在上篇博客——《Golang调度器(4)—goroutine调度》中一
- 使用一个例子说明golang如何访问和修改json文件;主要分三步:从文件读入json串把json串转变成golang对象遍历或者修改jso
- 目录01 — Pytest核心功能02 — 创建测试项目03 — 编写测试用例04 — 执行测试用例05 — 数据与脚本分离06 — 参数化
- pycharm简介PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语
- 使用jmail组件发送邮件:Function JMail(Send_From,Send_To,Send_Subject,Send_