Pythonic【15个代码示例】
Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。
要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,Github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里收集了一些常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。

变量交换
- Bad
tmp = a
a = b
b = tmp
- Pythonic
a,b = b,a
列表推导
- Bad
my_list = []
for i in range(10):
my_list.append(i*2)
- Pythonic
my_list = [i*2 for i in range(10)]
单行表达式
- 虽然列表推导式由于其简洁性及表达性,被广受推崇。
- 但是有许多可以写成单行的表达式,并不是好的做法。
- 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
带索引遍历
- Bad
for i in range(len(my_list)):
print(i, "-->", my_list[i])
- Pythonic
for i,item in enumerate(my_list):
print(i, "-->",item)
序列解包
- 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
1
字符串拼接
- Bad
letters = ['s', 'p', 'a', 'm']
s=""
for let in letters:
s += let
- Pythonic
letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)
真假判断
- 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!'
访问字典元素
- 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']
操作列表
- 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)
文件读取
- 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
代码续行
- 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)
显式代码
- Bad
def make_complex(*args):
x, y = args
return dict(**locals())
- Pythonic
def make_complex(x, y):
return {'x': x, 'y': y}
使用占位符
- Pythonic
filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')
链式比较
- Bad
if age > 18 and age < 60:
print("young man")
- Pythonic
if 18 < age < 60:
print("young man")
- 理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False
>>> False == False == True
False
三目运算
这个保留意见。随使用习惯就好。
- Bad
if a > 2:
b = 2
else:
b = 1
#b = 2
- Pythonic
a = 3 b = 2 if a > 2 else 1
#b = 2
关注、留言,我们一起学习,您的收藏是我持续更新的动力!
===============Talk is cheap, show me the code,bye-bye================
Pythonic【15个代码示例】的更多相关文章
- Java8-Function使用及Groovy闭包的代码示例
导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...
- Python实现各种排序算法的代码示例总结
Python实现各种排序算法的代码示例总结 作者:Donald Knuth 字体:[增加 减小] 类型:转载 时间:2015-12-11我要评论 这篇文章主要介绍了Python实现各种排序算法的代码示 ...
- [转]如何利用ndk-stack工具查看so库的调用堆栈【代码示例】?
如何利用ndk-stack工具查看so库的调用堆栈[代码示例]? http://hi.baidu.com/subo4110/item/d00395b3bf63e4432bebe36d Step1:An ...
- Web前端设计:Html强制不换行<nobr>标签用法代码示例
在网页排版布局中比如文章列表标题排版,无论多少文字均不希望换行显示,需要强制在一行显示完内容.这就可以nobr标签来实现.它起到的作用与word-break:keep-all 是一样的.nobr 是 ...
- Delphi之通过代码示例学习XML解析、StringReplace的用法(异常控制 good)
*Delphi之通过代码示例学习XML解析.StringReplace的用法 这个程序可以用于解析任何合法的XML字符串. 首先是看一下程序的运行效果: 以解析这样一个XML的字符串为例: <? ...
- 中文代码示例之Angular入门教程尝试
原址: https://zhuanlan.zhihu.com/p/30853705 原文: 中文代码示例教程之Angular尝试 为了检验中文命名在Angular中的支持程度, 把Angular官方入 ...
- RSA加密传输代码示例
RSA加密传输代码示例 涉及敏感数据的传输,双方最好约定使用加密解密.那RSA非对称加密就大有作为了.服务端可以保留自己的私钥,发给客户端对应的公钥.这样就可以互相加解密了.php中rsa加解密实现: ...
- 2017-11-07 中文代码示例之Angular入门教程尝试
"中文编程"知乎专栏原址 原文: 中文代码示例教程之Angular尝试 为了检验中文命名在Angular中的支持程度, 把Angular官方入门教程的示例代码中尽量使用了中文命名. ...
- 【Java基础】2、Java中普通代码块,构造代码块,静态代码块区别及代码示例
Java中普通代码块,构造代码块,静态代码块区别及代码示例.Java中普通代码块,构造代码块,静态代码块区别及代码示例 执行顺序:静态代码块>静态方法(main方法)>构造代码块>构 ...
随机推荐
- SpringMVC-结果跳转方式
结果跳转方式 目录 结果跳转方式 1. ModelAndView 2. ServletAPI 3. SpringMVC实现 1. 无需视图解析器 2. 使用视图解析器 1. ModelAndView ...
- go http请求流程分析
前言 golang作为常驻进程, 请求第三方服务或者资源(http, mysql, redis等)完毕后, 需要手动关闭连接, 否则连接会一直存在; 连接池是用来管理连接的, 请求之前从连接池里获取连 ...
- FFmpeg开发笔记(四):ffmpeg解码的基本流程详解
若该文为原创文章,未经允许不得转载原博主博客地址:https://blog.csdn.net/qq21497936原博主博客导航:https://blog.csdn.net/qq21497936/ar ...
- python 3 continue 循环控制
- Magicodes.IE 2.3重磅发布——.NET Core开源导入导出库
在2.3这一版本的更新中,我们迎来了众多的使用者.贡献者,在这个里程碑中我们也添加并修复了一些功能.对于新特点的功能我将在下面进行详细的描述,当然也欢迎更多的人可以加入进来,再或者也很期待大家来提is ...
- MYsql添加用户、赋予权限
1.创建新用户 CREATE USER 'admin'@'%' IDENTIFIED BY '123456'; '%' 表示可以远程登录访问.操作 ‘localhost’ 表示只能本地登录访问.操作2 ...
- 基于DDD+微服务的开发实战(1)
1 DDD是什么? DDD是领域驱动设计,是Eric Evans于2003年提出的,离现在有17年. 2 为什么需要DDD 当软件越来越复杂,实际开发中,大量的业务逻辑堆积在一个巨型类中的例子屡见不鲜 ...
- Java编程系列文章序言
Java编程系列分为基础编程和高级编程两部分: 其中基础编程包括基础语法如变量和标识符,流程控制等,数组如一维数组二位数组等,及面向对象,异常处理: 高级部分多线程,常用类,注解,Java集合,泛型, ...
- java关键字static和final
static可以修饰变量,方法或者类(普通类是不能用static修饰的,只能用来修饰内部类) static静态变量又称之为类变量(和c++中的全局变量概念是一样的),在类加载后,jvm只为类变量分配一 ...
- day55:django:cookie&session
目录 1.Cookie 1.Cookie前戏 2.Cookie的引入 3.django中操作cookie 2.Session 1.cookie的局限性 2.session技术 3.django操作se ...