值得收藏!15个 Pythonic 的代码示例

值得收藏!15个 Pythonic 的代码示例Python 由于语言的简洁性 让我们以人类思考的方式来写代码 新手更容易上手 老鸟更爱不释手 要写出 Pythonic 优雅的 地道的 整洁的 代码 还要平时多观察那些大牛代码 Github 上有很多非常优秀的源代码值得阅读 比如 requests flask tornado 这里小明收集了一些常见的 Pythonic 写法 帮助你养成写优秀代码的习惯 01 变量交换 Badtmp aa bb tmpPythonica b b a02 列表推导 Badmy list

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

文末福利

本人原创的 《PyCharm 中文指南》一书前段时间一经发布,就火爆了整个 Python 圈,发布仅一天的时间,下载量就突破了 1000 ,并且在当天就在 Github 上就收获了数百的 star,截至目前,下载量已经破万。

这本书一共将近 200 页内含大量的图解制作之精良,值得每个 Python 工程师 人手一份。

值得收藏!15个 Pythonic 的代码示例

为方便你下载,我将这本书上传到 百度网盘上了,你可以自行获取。

链接:https://pan.baidu.com/s/1-NzATHFtaTV1MQzek70iUQ

密码:mft3

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233972.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 关闭eslint检测[通俗易懂]

    关闭eslint检测[通俗易懂]bulid>webpack.base.config.js将createLintingRule方法内容注释转载文章关闭eslint检测

    2022年5月1日
    49
  • Kafka、RabbitMQ、RocketMQ等消息中间件的介绍和对比「建议收藏」

    Kafka、RabbitMQ、RocketMQ等消息中间件的介绍和对比

    2022年2月12日
    45
  • goland2021激活码_在线激活[通俗易懂]

    (goland2021激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.htmlMLZPB5EL5Q-eyJsaWN…

    2022年3月21日
    162
  • 【学习强化学习】十三、模仿学习介绍[通俗易懂]

    【学习强化学习】十三、模仿学习介绍[通俗易懂]文章目录参考资料1.模仿学习概述2.行为克隆2.1行为克隆缺点缺点1:观测非常有限缺点2:机器会完全模仿专家的行为缺点3:训练数据跟测试数据不匹配2.逆强化学习2.1概述2.2奖励函数2.2IRLvsGAN3.第三人称视角模仿学习4.练习4.1keywords参考资料https://datawhalechina.github.io/easy-rl/#/chapter11/chapter111.模仿学习概述模仿学习(imitationlearning,IL)又叫做示范学习(

    2022年9月19日
    0
  • ue4安装插件_ue4 软引用

    ue4安装插件_ue4 软引用原创文章,转载请注明出处。本文介绍两个知识点Plugin/Module插件和模块的联系区别,同时介绍插件和我们的Source中创建多模块。**一、Plugin/Module插件和模块的联系区别**1>一个插件至少有一个模块2>一般插件都是做底层做通用设计的,而模块做的负责的我理解为逻辑ProjectName.Build.cs //主要管理的是链接,dll的链接ProjectName.Target.cs //管理的是编译,加上才会编译你的Module,如果你是run

    2022年10月4日
    0
  • 锁定屏幕相关知识「建议收藏」

    锁定屏幕相关知识「建议收藏」  (1)LockWorkStation()锁定当前用户返回到登录界面 (2)HKEY_CURRENT_USER/Software/Microsoft/Windows/CurentVersion/Polioies/Explores下的”NoSaveSetting”值为1则禁止修改桌面(需要重启) (3)HKEY_CURRENT_USER/Software//microsof

    2022年7月21日
    16

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号