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方法)>构造代码块>构 ...
随机推荐
- sqlserver语句的执行顺序
执行顺序: 1.from 2.where 3.group by 4.having 5.根据select 关键之后的要显示的字段,进行结果集显示 6.order by 对最终结果集进行排序 7.top/ ...
- SpringMVC执行流程源码分析
SpringMVC执行流程源码分析 我们先来看张图片,帮助我们理解整个流程 然后我们开始来解析 首先SpringMVC基于Servlet来运行 那么我们首先来看HttpServletBean这个类 他 ...
- 理解Spring AOP的实现方式与思想
Spring AOP简介 如果说IOC是Spring的核心,那么面向切面编程就是Spring最核心的功能之一了,在数据库事务中,面向切面编程被广泛应用. AOP能够将那些与业务无关,却为业务模块所共同 ...
- WinDbg排查CPU高的问题
一.概述 在Window服务器部署程序后,可能因为代码的不合理或者其他各种各样的问题,会导致CPU暴增,甚至达到100%等情况,严重危及到服务器的稳定以及系统稳定,但是一般来说对于已发布的程序,没法即 ...
- 第23课 - #error 和 #line 使用分析
第23课 - #error 和 #line 使用分析 1. #error 的用法 (1)#error 是一个预处理器指示字,用于生成一个编译错误消息,这个消息最终会传递到编译器(gcc) 在思考这一点 ...
- 跨平台框架与React Native基础
跨平台框架 什么是跨平台框架? 这里的多个平台一般是指 iOS 和 Android . 为什么需要跨平台框架? 目前,移动开发技术主要分为原生开发和跨平台开发两种.其中,原生应用是指在某个特定的移动平 ...
- Java 异常面试题(2020 最新版)
Java异常架构与异常关键字 Java异常简介 Java异常是Java提供的一种识别及响应错误的一致性机制. Java异常机制可以使程序中异常处理代码和正常业务代码分离,保证程序代码更加优雅,并提高程 ...
- java 常用类-String-1
一.字符串相关的类 1.1 String 的特性 String类:代表字符串.Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现. String是一个fin ...
- 基于python的extract_msg模块提取outlook邮箱保存的msg文件中的附件
笔者保存了一些outlook邮箱中保存的一些msg格式的邮件文件,现需要将其中的附件提取出来, 当然直接在outlook中就可以另存附件,但outlook默认是不支持批量提取邮件中的附件的 思考过几种 ...
- Centos-用户管理-useradd userdel usermod groupadd groupdel id
linux是多用户.多任务操作系统 linux角色分类 超级用户 root # 管理员.特定服务主进程 0 普通用户 $ 普通管理员.服务运行需要的用户 500~65535 虚拟用户 不能登录 ...