15个Pythonic的代码示例(值得收藏)


Posted in Python onOctober 29, 2020

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

到此这篇关于15个Pythonic的代码示例(值得收藏)的文章就介绍到这了,更多相关Pythonic代码内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python 字符串split的用法分享
Mar 23 Python
python PIL模块与随机生成中文验证码
Feb 27 Python
python将秒数转化为时间格式的实例
Sep 16 Python
Python中Numpy ndarray的使用详解
May 24 Python
python tkinter canvas 显示图片的示例
Jun 13 Python
PyQt5重写QComboBox的鼠标点击事件方法
Jun 25 Python
python 将日期戳(五位数时间)转换为标准时间
Jul 11 Python
Python3分析处理声音数据的例子
Aug 27 Python
Pytorch 实现计算分类器准确率(总分类及子分类)
Jan 18 Python
scrapy数据存储在mysql数据库的两种方式(同步和异步)
Feb 18 Python
Python 使用dict实现switch的操作
Apr 07 Python
分享提高 Python 代码的可读性的技巧
Mar 03 Python
python 如何设置守护进程
Oct 29 #Python
python 多线程中join()的作用
Oct 29 #Python
pycharm2020.1.2永久破解激活教程,实测有效
Oct 29 #Python
python 实现音频叠加的示例
Oct 29 #Python
详解python的super()的作用和原理
Oct 29 #Python
Python生成pdf目录书签的实例方法
Oct 29 #Python
利用python清除移动硬盘中的临时文件
Oct 28 #Python
You might like
php邮件发送,php发送邮件的类
2011/03/24 PHP
php强制更新图片缓存的方法
2015/02/11 PHP
Linux下编译redis和phpredis的方法
2016/04/07 PHP
js利用prototype调用Array的slice方法示例
2014/06/09 Javascript
JavaScript使用位运算符判断奇数和偶数的方法
2015/06/01 Javascript
jQuery Validation Engine验证控件调用外部函数验证的方法
2017/01/18 Javascript
JavaScript中的编码和解码函数
2017/02/15 Javascript
ES6实现的遍历目录函数示例
2017/04/07 Javascript
js/jquery遍历对象和数组的方法分析【forEach,map与each方法】
2019/02/27 jQuery
从理论角度讨论JavaScript闭包
2019/04/03 Javascript
详解VUE调用本地json的使用方法
2019/05/15 Javascript
小程序跳转到的H5页面再跳转回跳小程序的方法
2020/03/06 Javascript
js实现删除json中指定的元素
2020/09/22 Javascript
python益智游戏计算汉诺塔问题示例
2014/03/05 Python
从零学python系列之新版本导入httplib模块报ImportError解决方案
2014/05/23 Python
用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动
2015/11/05 Python
Python双精度浮点数运算并分行显示操作示例
2017/07/21 Python
详解Python爬取并下载《电影天堂》3千多部电影
2019/04/26 Python
Python实现计算文件MD5和SHA1的方法示例
2019/06/11 Python
Python进程,多进程,获取进程id,给子进程传递参数操作示例
2019/10/11 Python
JAVA及PYTHON质数计算代码对比解析
2020/06/10 Python
解锁canvas导出图片跨域的N种姿势小结
2019/01/24 HTML / CSS
Lee牛仔裤澳大利亚官网:美国著名牛仔裤品牌
2017/09/02 全球购物
京东国际站:JOYBUY
2017/11/23 全球购物
便携式太阳能系统的创新者:GOAL ZERO
2018/02/04 全球购物
高中微机老师自我鉴定
2014/02/16 职场文书
小学雷锋月活动总结
2014/07/03 职场文书
治庸问责工作总结
2015/08/11 职场文书
班级班风口号大全
2015/12/25 职场文书
2016学习全国教书育人楷模先进事迹心得体会
2016/01/21 职场文书
python使用XPath解析数据爬取起点小说网数据
2021/04/22 Python
Goland使用Go Modules创建/管理项目的操作
2021/05/06 Golang
MySQL令人大跌眼镜的隐式转换
2021/08/23 MySQL
Android超详细讲解组件ScrollView的使用
2022/03/31 Java/Android
Window server 2012 R2 AD域的组策略相关设置
2022/04/28 Servers
SQL Server2019安装的详细步骤实战记录(亲测可用)
2022/06/10 SQL Server