瞧瞧,这样的代码才叫 Pythonic

开发 前端
要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,这里明哥收集了一些比较常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。

Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。

要写出 Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,这里明哥收集了一些比较常见的 Pythonic 写法,帮助你养成写优秀代码的习惯。

1. 变量交换

交换两个变量的值,正常都会想利用一个中间临时变量来过渡。

  1. tmp = a 
  2. a = b 
  3. b = tmp 

能用一行代码解决的(并且不影响可读性的),决不用三行代码。

  1. a,bb = b,a 

2. 列表推导

下面是一个非常简单的 for 循环。

  1. my_list = [] 
  2. for i in range(10): 
  3.     my_list.append(i*2) 

在一个 for 循环中,如果逻辑比较简单,不如试用一下列表的列表推导式,虽然只有一行代码,但也逻辑清晰。

  1. my_list = [i*2 for i in range(10)] 

3. 单行表达式

上面两个案例,都将多行代码用另一种方式写成了一行代码。

这并不意味着,代码行数越少,就越 Pythonic 。

比如下面这样写,就不推荐。

  1. print('hello'); print('world') 
  2.  
  3. if x == 1: print('hello,world') 
  4.  
  5. if <complex comparison> and <other complex comparison>
  6.     # do something 

建议还是按照如下的写法来

  1. print('hello') 
  2. print('world') 
  3.  
  4. if x == 1: 
  5.     print('hello,world') 
  6.  
  7. cond1 = <complex comparison> 
  8. cond2 = <other complex comparison> 
  9. if cond1 and cond2: 
  10.     # do something 

4. 带索引遍历

使用 for 循环时,如何取得对应的索引,初学者习惯使用 range + len 函数

  1. for i in range(len(my_list)): 
  2.     print(i, "-->", my_list[i]) 

更好的做法是利用 enumerate 这个内置函数

  1. for i,item in enumerate(my_list): 
  2.     print(i, "-->",item) 

5. 序列解包

使用 * 可以对一个列表解包

  1. a, *rest = [1, 2, 3] 
  2. a = 1rest = [2, 3] 
  3.  
  4. a, *middle, c = [1, 2, 3, 4] 
  5. a = 1middle = [2, 3], c = 4 

6. 字符串拼接

如果一个列表(或者可迭代对象)中的所有元素都是字符串对象,想要将他们连接起来,通常做法是

  1. letters = ['s', 'p', 'a', 'm'] 
  2. s="" 
  3. for let in letters: 
  4.     s += let 

更推荐的做法是使用 join 函数

  1. letters = ['s', 'p', 'a', 'm'] 
  2. word = ''.join(letters) 

7. 真假判断

判断一个变量是否为真(假),新手习惯直接使用 == 与 True、False、None 进行对比

  1. if attr == True: 
  2.     print('True!') 
  3.  
  4. if attr == None: 
  5.     print('attr is None!') 

实际上,""、[]、{} 这些没有任何元素的容器都是假值,可直接使用 if not xx 来判断。

  1. if attr: 
  2.     print('attr is truthy!') 
  3.  
  4. if not attr: 
  5.     print('attr is falsey!') 

8. 访问字典元素

当直接使用 [] 来访问字典里的元素时,若key不存在,是会抛异常的,所以新会可能会先判断一下是否有这个 key,有再取之。

  1. d = {'hello': 'world'} 
  2. if d.has_key('hello'): 
  3.     print(d['hello'])    # prints 'world' 
  4. else: 
  5.     print('default_value') 

更推荐的做法是使用 get 来取,如果没有该 key 会默认返回 None(当然你也可以设置默认返回值)

  1. d = {'hello': 'world'} 
  2.  
  3. print(d.get('hello', 'default_value')) # prints 'world' 
  4. print(d.get('thingy', 'default_value')) # prints 'default_value' 

9. 操作列表

下面这段代码,会根据条件过滤过列表中的元素

  1. a = [3, 4, 5] 
  2. b = [] 
  3. for i in a: 
  4.     if i > 4: 
  5.         b.append(i) 

实际上可以使用列表推导或者高阶函数 filter 来实现

  1. a = [3, 4, 5] 
  2. b = [i for i in a if i > 4] 
  3. # Or: 
  4. b = filter(lambda x: x > 4, a) 

除了 filter 之外,还有 map、reduce 这两个函数也很好用

  1. a = [3, 4, 5] 
  2. b = map(lambda i: i + 3, a) 
  3. # b: [6,7,8] 

10. 文件读取

文件读取是非常常用的操作,在使用完句柄后,是需要手动调用 close 函数来关闭句柄的

  1. fp = open('file.txt') 
  2. print(fp.read()) 
  3. fp.close() 

如果代码写得太长,即使你知道需要手动关闭句柄,却也会经常会漏掉。因此推荐养成习惯使用 with open 来读写文件,上下文管理器会自动执行关闭句柄的操作

  1. with open('file.txt') as fp: 
  2.     for line in fp.readlines(): 
  3.         print(line) 

11. 代码续行

将一个长度较长的字符串放在一行中,是很影响代码可读性的(下面代码可向左滑动)

  1. long_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.”' 

稍等注重代码可读性的人,会使用三个引号 \来续写

  1. long_string = 'For a long time I used to go to bed early. ' \ 
  2.               'Sometimes, when I had put out my candle, ' \ 
  3.               'my eyes would close so quickly that I had not even time to say “I’m going to sleep.”' 

不过,对我来说,我更喜欢这样子写 使用括号包裹 ()

  1. long_string = ( 
  2.     "For a long time I used to go to bed early. Sometimes, " 
  3.     "when I had put out my candle, my eyes would close so quickly " 
  4.     "that I had not even time to say “I’m going to sleep.”" 

导包的时候亦是如此

  1. from some.deep.module.inside.a.module import ( 
  2.     a_nice_function, another_nice_function, yet_another_nice_function) 

12. 显式代码

有时候出于需要,我们会使用一些特殊的魔法来使代码适应更多的场景不确定性。

  1. def make_complex(*args): 
  2.     x, y = args 
  3.     return dict(**locals()) 

但若非必要,请不要那么做。无端增加代码的不确定性,会让原先本就动态的语言写出更加动态的代码。

  1. def make_complex(x, y): 
  2.     return {'x': x, 'y': y} 

13. 使用占位符

对于暂不需要,却又不得不接收的的变量,请使用占位符

  1. filename = 'foobar.txt' 
  2. basename, _, ext = filename.rpartition('.') 

14. 链式比较

对于下面这种写法

  1. score = 85 
  2. if score > 80 and score < 90: 
  3.     print("良好") 

其实还有更好的写法

  1. score = 85 
  2. if 80 < score < 90: 
  3.     print("良好") 

如果你理解了上面的链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False

  1. >>> False == False == True  
  2. False 

15. 三目运算

对于简单的判断并赋值

  1. age = 20 
  2. if age > 18: 
  3.     type = "adult" 
  4. else: 
  5.     type = "teenager" 

其实是可以使用三目运算,一行搞定。

  1. age = 20   
  2. b = "adult" if age > 18 else "teenager" 

 

责任编辑:赵宁宁 来源: Python编程时光
相关推荐

2017-09-08 12:15:54

Python代码Pythonic

2017-07-27 16:18:18

开源项目使用

2012-08-27 09:36:51

程序员创业读书

2022-02-17 07:54:55

VSCodeLinux内核

2021-02-19 23:55:15

PythonPythonic数据

2023-03-23 22:46:38

Spring限流机制

2021-02-05 11:36:42

数据业务指标

2023-02-06 12:00:00

重构PythonPythonic

2023-09-26 12:04:15

重构技巧Pythonic

2023-01-11 11:35:40

重构PythonPythonic

2021-04-20 10:50:38

Spring Boot代码Java

2022-08-19 14:24:30

forPythonpythonic

2016-11-09 20:21:12

简历开源时间管理工具编程语言

2020-05-15 15:28:51

爬虫Python学习

2022-04-24 08:23:19

Redis内存淘汰策略

2015-06-25 19:28:46

UI界面UI设计

2015-09-21 09:38:14

营销H5

2017-09-14 12:03:30

大数据数据分析语言

2015-09-21 11:34:59

H5发展

2023-08-01 08:54:02

接口幂等网络
点赞
收藏

51CTO技术栈公众号