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创建和删除目录的方法
Apr 29 Python
Python中使用items()方法返回字典元素对的教程
May 21 Python
常用python编程模板汇总
Feb 12 Python
python 写的一个爬虫程序源码
Feb 28 Python
python使用pil进行图像处理(等比例压缩、裁剪)实例代码
Dec 11 Python
网红编程语言Python将纳入高考你怎么看?
Jun 07 Python
详解将Python程序(.py)转换为Windows可执行文件(.exe)
Jul 19 Python
PyTorch之图像和Tensor填充的实例
Aug 18 Python
Numpy中对向量、矩阵的使用详解
Oct 29 Python
pyhton中__pycache__文件夹的产生与作用详解
Nov 24 Python
PyPDF2读取PDF文件内容保存到本地TXT实例
May 12 Python
最新PyCharm 2020.2.3永久激活码(亲测有效)
Nov 26 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
Syphon 秘笈
2021/03/03 冲泡冲煮
MySQL数据库转移,access,sql server 转 MySQL 的图文教程
2007/09/02 PHP
Uchome1.2 1.5 代码学习 common.php
2009/04/24 PHP
PHP 木马攻击防御技巧
2009/06/13 PHP
php数组函数序列之array_key_exists() - 查找数组键名是否存在
2011/10/29 PHP
php 判断是否是中文/英文/数字示例代码
2013/09/30 PHP
php使用explode()函数将字符串拆分成数组的方法
2015/02/17 PHP
特殊字符、常规符号及其代码对照表
2006/06/26 Javascript
js 分页全选或反选标识实现代码
2011/08/09 Javascript
jquery tab插件精简版分享
2011/09/10 Javascript
JQuery 返回布尔值Is()条件判断方法代码
2012/05/14 Javascript
Jquery增加鼠标中间功能mousewheel的实例代码
2013/09/05 Javascript
用js读、写、删除Cookie代码分享及详细注释说明
2014/06/05 Javascript
详解JavaScript的Polymer框架中的通知交互
2015/07/29 Javascript
BootStrap表单控件之复选框checkbox和单选择按钮radio
2017/05/23 Javascript
详谈innerHTML innerText的使用和区别
2017/08/18 Javascript
js实现各浏览器全屏代码实例
2018/07/03 Javascript
JS调用安卓手机摄像头扫描二维码
2018/10/16 Javascript
vue路由的配置和页面切换详解
2020/09/09 Javascript
Python实现扫描指定目录下的子目录及文件的方法
2014/07/16 Python
Python实现从url中提取域名的几种方法
2014/09/26 Python
Python抓取框架 Scrapy的架构
2016/08/12 Python
Python3 加密(hashlib和hmac)模块的实现
2017/11/23 Python
基于numpy.random.randn()与rand()的区别详解
2018/04/17 Python
anaconda中更改python版本的方法步骤
2019/07/14 Python
python使用yield压平嵌套字典的超简单方法
2019/11/02 Python
python pip如何手动安装二进制包
2020/09/30 Python
德国家具在线:Fashion For Home
2017/03/11 全球购物
大学校园生活自我鉴定
2014/01/13 职场文书
企业法律事务工作总结
2015/08/11 职场文书
Jupyter notebook 不自动弹出网页的解决方案
2021/05/21 Python
Python3中最常用的5种线程锁实例总结
2021/07/07 Python
分享CSS盒子模型隐藏的几种方式
2022/02/28 HTML / CSS
Python实现日志实时监测的示例详解
2022/04/06 Python
mysql 子查询的使用
2022/04/28 MySQL
搭建zabbix监控以及邮件报警的超级详细教学
2022/07/15 Servers