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

 更新时间:2020年10月29日 11:12:11   投稿:zx  
这篇文章主要介绍了15个Pythonic的代码示例(值得收藏),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

到此这篇关于15个Pythonic的代码示例(值得收藏)的文章就介绍到这了,更多相关Pythonic代码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现LRU算法

    Python实现LRU算法

    这篇文章主要为大家详细介绍了Python实现LRU缓存置换算法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • python pandas中的agg函数用法

    python pandas中的agg函数用法

    这篇文章主要介绍了python pandas中的agg函数用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • Python3实现定时任务的四种方式

    Python3实现定时任务的四种方式

    Python实现定点与定时任务方式比较多,找到下面四中实现方式,每个方式都有自己应用场景;下面来快速介绍Python中常用的定时任务实现方式,一起看看吧
    2019-06-06
  • pyqt5中动画的使用详解

    pyqt5中动画的使用详解

    这篇文章主要介绍了pyqt5中动画的使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Python实现猜数字小游戏

    Python实现猜数字小游戏

    这篇文章介绍了Python实现猜数字小游戏,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以收藏下,方便下次浏览观看
    2021-12-12
  • 三步解决python PermissionError: [WinError 5]拒绝访问的情况

    三步解决python PermissionError: [WinError 5]拒绝访问的情况

    这篇文章主要介绍了三步解决python PermissionError: [WinError 5]拒绝访问的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Python编程实现控制cmd命令行显示颜色的方法示例

    Python编程实现控制cmd命令行显示颜色的方法示例

    这篇文章主要介绍了Python编程实现控制cmd命令行显示颜色的方法,结合实例形式分析了Python针对命令行字符串显示颜色属性相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • python实现解数独程序代码

    python实现解数独程序代码

    最近在带孩子学习数独,职业使然,就上网搜了下相关程序的解法,这里分享给大家,希望对大家学习python有所帮助
    2017-04-04
  • mac下pip、conda、homebrew修改为清华镜像源的方法

    mac下pip、conda、homebrew修改为清华镜像源的方法

    本文主要介绍了mac下pip、conda、homebrew修改为清华镜像源的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • python在控制台输出进度条的方法

    python在控制台输出进度条的方法

    这篇文章主要介绍了python在控制台输出进度条的方法,实例分析了Python输出进度条效果的方法,需要的朋友可以参考下
    2015-06-06

最新评论