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方法)>构造代码块>构 ...
随机推荐
- 用Python写一个向数据库填充数据的小工具
一. 背景 公司又要做一个新项目,是一个合作型项目,我们公司出web展示服务,合作伙伴线下提供展示数据. 而且本次项目是数据统计展示为主要功能,并没有研发对应的数据接入接口,所有展示数据源均来自数据库 ...
- oracle之三rman 完全恢复
rman 完全恢复 8.1 recover 恢复: 1)归档 : 完全恢复和不完全恢复 2)非归档:只能恢复到最后一次备份状态(还原) 8.2 完全恢复: ----先对数据库做一个备份(如果是arch ...
- dict字典,以及字典的一些基本应用
dict表示方法: dict={}或d=dict() 1.字典的增:d['元素名']='元素值'.或d.setdefault('key','value') 2.字典的删:d.pop(key).或del ...
- 使用vscode编辑和提交github仓库代码
写在前面 在github上想删除仓库中的某个文件或文件夹,亦或是重命名操作都很麻烦,这里提供一种vscode的解决方案.在vscode中克隆远程github仓库,然后对代码或文件进行编辑,最后提交即可 ...
- [Node]创建静态资源服务器
项目初始化 .gitignore cnpm i eslint -D eslint --init得到.eslintrc.js .eslintrc.js module.exports = { 'env': ...
- 原生post请求
ajax: function(opt) { opt = opt || {}; opt.method = opt.method.toUpperCase() || 'POST'; opt.url = op ...
- Python爬虫和函数调试
一:函数调试 用之前学过的try···except进行调试 def gameover(setA,setB): if setA==3 or setB==3: return True else: retu ...
- 3.Channel详解
- dubbo学习(七)dubbo项目搭建--生产者(服务提供者)
PS: 项目架子以及工程间的maven依赖配置暂时省略,后续看情况可能会单独写一篇文章捋捋框架结构,先马克~ 配置和启动 1.pom文件引入dubbo和zookeeper的操作客户端 <!-- ...
- (最新 9000 字 )Spring Boot 配置特性解析
爱生活,爱编码,微信搜一搜[架构技术专栏]关注这个喜欢分享的地方.本文 架构技术专栏 已收录,有各种JVM.多线程.源码视频.资料以及技术文章等你来拿 一.概述 目前Spring Boot版本: 2. ...