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实现的一个火车票转让信息采集器
Jul 09 Python
Python常见异常分类与处理方法
Jun 04 Python
Python编程实现的简单Web服务器示例
Jun 22 Python
python计算auc指标实例
Jul 13 Python
解决Python网页爬虫之中文乱码问题
May 11 Python
Python实现将HTML转成PDF的方法分析
May 04 Python
Pandas透视表(pivot_table)详解
Jul 22 Python
python如何获取apk的packagename和activity
Jan 10 Python
解决python图像处理图像赋值后变为白色的问题
Jun 04 Python
拿来就用!Python批量合并PDF的示例代码
Aug 10 Python
python 如何将office文件转换为PDF
Sep 22 Python
python 基于selectors库实现文件上传与下载
Dec 31 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代码DOS造成用光网络带宽
2011/03/01 PHP
PHP中通过语义URL防止网站被攻击的方法分享
2011/09/08 PHP
基于php冒泡排序算法的深入理解
2013/06/09 PHP
Laravel框架分页实现方法分析
2018/06/12 PHP
使用tp框架和SQL语句查询数据表中的某字段包含某值
2019/10/18 PHP
由JavaScript技术实现的web小游戏(不含网游)
2010/06/12 Javascript
jQuery .attr()和.removeAttr()方法操作元素属性示例
2013/07/16 Javascript
JavaScript中按位“异或”运算符使用介绍
2014/03/14 Javascript
Bootstrap缩略图与警告框学习使用
2017/02/08 Javascript
jquery hover 不停闪动问题的解决方法(亦为stop()的使用)
2017/02/10 Javascript
Vue.directive自定义指令的使用详解
2017/03/10 Javascript
angularjs实现猜数字大小功能
2020/05/20 Javascript
AngularJS中scope的绑定策略实例分析
2017/10/30 Javascript
详解NodeJS Https HSM双向认证实现
2019/03/12 NodeJs
Python3实现生成随机密码的方法
2014/08/23 Python
Python爬取网易云音乐上评论火爆的歌曲
2017/01/19 Python
Python实现的选择排序算法示例
2017/11/29 Python
python如何实现int函数的方法示例
2018/02/19 Python
如何使用VSCode愉快的写Python于调试配置步骤
2018/04/06 Python
Python从列表推导到zip()函数的5种技巧总结
2019/10/23 Python
IronPython连接MySQL的方法步骤
2019/12/27 Python
pytorch实现Tensor变量之间的转换
2020/02/17 Python
django有哪些好处和优点
2020/09/01 Python
Linux系统下升级pip的完整步骤
2021/01/31 Python
详解CSS3 弹性布局快速入门
2019/06/06 HTML / CSS
html5+css3气泡组件的实现
2014/11/21 HTML / CSS
上课迟到检讨书
2014/02/19 职场文书
运动会入场口号
2014/06/07 职场文书
建筑工地大门标语
2014/06/18 职场文书
公安局负责人查摆问题及整改方案
2014/09/27 职场文书
2014年维稳工作总结
2014/11/18 职场文书
五年级小学生评语
2014/12/26 职场文书
党员干部廉政承诺书
2015/04/28 职场文书
创业计划书之便利店
2019/09/05 职场文书
Django中session进行权限管理的使用
2021/07/09 Python
win10更新失败无限重启解决方法
2022/04/19 数码科技