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将MongoDB里的ObjectId转换为时间戳的方法
Mar 13 Python
python开发之基于thread线程搜索本地文件的方法
Nov 11 Python
python bmp转换为jpg 并删除原图的方法
Oct 25 Python
在pycharm上mongodb配置及可视化设置方法
Nov 30 Python
Django中信号signals的简单使用方法
Jul 04 Python
Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释
Jan 25 Python
Tensorflow中tf.ConfigProto()的用法详解
Feb 06 Python
python实现串口通信的示例代码
Feb 10 Python
Python如何根据时间序列数据作图
May 12 Python
django rest framework 自定义返回方式
Jul 12 Python
python selenium 获取接口数据的实现
Dec 07 Python
matplotlib制作雷达图报错ValueError的实现
Jan 05 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 截取字符串专题集合
2010/08/19 PHP
跟我学Laravel之安装Laravel
2014/10/15 PHP
PHP简单计算两个时间差的方法示例
2017/06/20 PHP
HTML长文本截取含有HTML代码同样适用的两种方法
2013/07/31 Javascript
JavaScript设计模式开发中组合模式的使用教程
2016/05/18 Javascript
javascript事件冒泡简单示例
2016/06/20 Javascript
完美解决jQuery fancybox ie 无法显示关闭按钮的问题
2016/11/29 Javascript
基于Vue生产环境部署详解
2017/09/15 Javascript
mockjs,json-server一起搭建前端通用的数据模拟框架教程
2017/12/18 Javascript
react-native-video实现视频全屏播放的方法
2018/03/19 Javascript
JS弹窗 JS弹出DIV并使整个页面背景变暗功能的实现代码
2018/04/21 Javascript
angularjs 动态从后台获取下拉框的值方法
2018/08/13 Javascript
angular ng-model 无法获取值的处理方法
2018/10/02 Javascript
webpack打包非模块化js的方法
2018/10/24 Javascript
图文讲解vue的v-if使用方法
2019/02/11 Javascript
微信小程序利用swiper+css实现购物车商品删除功能
2019/03/06 Javascript
解决vue 表格table列求和的问题
2019/11/06 Javascript
js实现数字从零慢慢增加到指定数字示例
2019/11/07 Javascript
iview实现图片上传功能
2020/06/29 Javascript
[00:33]2016完美“圣”典风云人物:Sccc宣传片
2016/12/03 DOTA
用Python实现KNN分类算法
2017/12/22 Python
Selenium元素的常用操作方法分析
2018/08/10 Python
Python操作多维数组输出和矩阵运算示例
2019/11/28 Python
centos7中安装python3.6.4的教程
2019/12/11 Python
如何使用python3获取当前路径及os.path.dirname的使用
2019/12/13 Python
台湾旅游网站:雄狮旅游网
2017/08/16 全球购物
Blank NYC官网:夹克、牛仔裤等
2020/12/16 全球购物
学校十一活动方案
2014/02/01 职场文书
公司活动方案范文
2014/03/06 职场文书
环境工程专业自荐信范文
2014/06/24 职场文书
2015年教师师德师风承诺书
2015/04/28 职场文书
离婚答辩状范文
2015/05/22 职场文书
详解MySQL 用户权限管理
2021/04/20 MySQL
详解MySQL数据库千万级数据查询和存储
2021/05/18 MySQL
浅谈Python numpy创建空数组的问题
2021/05/25 Python
css3手动实现pc端横向滚动
2022/06/21 HTML / CSS