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个代码示例】的更多相关文章

  1. Java8-Function使用及Groovy闭包的代码示例

    导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...

  2. Python实现各种排序算法的代码示例总结

    Python实现各种排序算法的代码示例总结 作者:Donald Knuth 字体:[增加 减小] 类型:转载 时间:2015-12-11我要评论 这篇文章主要介绍了Python实现各种排序算法的代码示 ...

  3. [转]如何利用ndk-stack工具查看so库的调用堆栈【代码示例】?

    如何利用ndk-stack工具查看so库的调用堆栈[代码示例]? http://hi.baidu.com/subo4110/item/d00395b3bf63e4432bebe36d Step1:An ...

  4. Web前端设计:Html强制不换行<nobr>标签用法代码示例

    在网页排版布局中比如文章列表标题排版,无论多少文字均不希望换行显示,需要强制在一行显示完内容.这就可以nobr标签来实现.它起到的作用与word-break:keep-all 是一样的.nobr 是 ...

  5. Delphi之通过代码示例学习XML解析、StringReplace的用法(异常控制 good)

    *Delphi之通过代码示例学习XML解析.StringReplace的用法 这个程序可以用于解析任何合法的XML字符串. 首先是看一下程序的运行效果: 以解析这样一个XML的字符串为例: <? ...

  6. 中文代码示例之Angular入门教程尝试

    原址: https://zhuanlan.zhihu.com/p/30853705 原文: 中文代码示例教程之Angular尝试 为了检验中文命名在Angular中的支持程度, 把Angular官方入 ...

  7. RSA加密传输代码示例

    RSA加密传输代码示例 涉及敏感数据的传输,双方最好约定使用加密解密.那RSA非对称加密就大有作为了.服务端可以保留自己的私钥,发给客户端对应的公钥.这样就可以互相加解密了.php中rsa加解密实现: ...

  8. 2017-11-07 中文代码示例之Angular入门教程尝试

    "中文编程"知乎专栏原址 原文: 中文代码示例教程之Angular尝试 为了检验中文命名在Angular中的支持程度, 把Angular官方入门教程的示例代码中尽量使用了中文命名. ...

  9. 【Java基础】2、Java中普通代码块,构造代码块,静态代码块区别及代码示例

    Java中普通代码块,构造代码块,静态代码块区别及代码示例.Java中普通代码块,构造代码块,静态代码块区别及代码示例 执行顺序:静态代码块>静态方法(main方法)>构造代码块>构 ...

随机推荐

  1. python3 for

    当range中只有一个参数时,此参数表示终点,但不包括.(从0开始) 当range中有两个参数时,分别表示起点和终点.(左闭但不包括终点) 当range中有三个参数时,分别表示起点和终点,和步长,意思 ...

  2. Robotframework自动化6-基础关键字介绍3

    这一章节介绍一下断言时用到的关键字,断言是写测试用例的必备,没有断言的测试用例是没有灵魂的. 一:Should Be Equal  Should Be Equal 是用来判断实践结果和预期结果是否一致 ...

  3. [Codeforces1174B]Ehab Is an Odd Person

    题目链接 https://codeforces.com/contest/1174/problem/B 题意 给一个数组,只能交换和为奇数的两个数,问最终能得到的字典序最小的序列. 题解 内心OS:由题 ...

  4. Fork Join 并发任务执行框架

    Fork Join 体现了分而治之 什么是分而治之? 规模为N的问题,如果N<阈值,直接解决,N>阈值,将N分解为K个小规模子问题,子问题互相对立,与原问题形式相同,将子问题的解合并得到原 ...

  5. Gradle系列之Android Gradle高级配置

    本篇文章主要在之前学习的基础上,从实际开发的角度学习如何对 Android Gradle 来进行自定义以满足不同的开发需求,下面是 Gradle 系列的几篇文章: Gradle系列之初识Gradle ...

  6. domReady的理解

    domReady的理解 domReady是名为DOMContentLoaded事件的别称,当初始的HTML文档被完全加载和解析完成之后,DOMContentLoaded事件被触发,而无需等待样式表.图 ...

  7. oh-my-zsh超级终端

    _ _ ___ | |__ _ __ ___ _ _ _______| |__ / _ \| '_ \ _____| '_ ` _ \| | | |____|_ / __| '_ \ | (_) | ...

  8. WEB 应用缓存解析以及使用 Redis 实现分布式缓存

    什么是缓存? 缓存就是数据交换的缓冲区,用于临时存储数据(使用频繁的数据).当用户请求数据时,首先在缓存中寻找,如果找到了则直接返回.如果找不到,则去数据库中查找.缓存的本质就是用空间换时间,牺牲数据 ...

  9. 《Java并发编程的艺术》笔记

    第1章 并发编程的挑战 1.1 上下文切换 CPU通过时间片分配算法来循环执行任务,任务从保存到再加载的过程就是一次上下文切换. 减少上下文切换的方法有4种:无锁并发编程.CAS算法.使用最少线程.使 ...

  10. Burp Suite的安装

    安装均在虚拟机环境下进行. 1.首先在浏览器找到java进行最新版本的安装. 2.然后找到burp suite 的安装包下载 不知道这一次 怎么直接跳过安装打开了.