自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

瞧瞧,這樣的代碼才叫 Pythonic

開發(fā) 前端
要寫出 Pythonic(優(yōu)雅的、地道的、整潔的)代碼,還要平時(shí)多觀察那些大牛代碼,這里明哥收集了一些比較常見的 Pythonic 寫法,幫助你養(yǎng)成寫優(yōu)秀代碼的習(xí)慣。

Python由于語(yǔ)言的簡(jiǎn)潔性,讓我們以人類思考的方式來(lái)寫代碼,新手更容易上手,老鳥更愛不釋手。

要寫出 Pythonic(優(yōu)雅的、地道的、整潔的)代碼,還要平時(shí)多觀察那些大牛代碼,這里明哥收集了一些比較常見的 Pythonic 寫法,幫助你養(yǎng)成寫優(yōu)秀代碼的習(xí)慣。

1. 變量交換

交換兩個(gè)變量的值,正常都會(huì)想利用一個(gè)中間臨時(shí)變量來(lái)過(guò)渡。

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

能用一行代碼解決的(并且不影響可讀性的),決不用三行代碼。

  1. a,bb = b,a 

2. 列表推導(dǎo)

下面是一個(gè)非常簡(jiǎn)單的 for 循環(huán)。

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

在一個(gè) for 循環(huán)中,如果邏輯比較簡(jiǎn)單,不如試用一下列表的列表推導(dǎo)式,雖然只有一行代碼,但也邏輯清晰。

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

3. 單行表達(dá)式

上面兩個(gè)案例,都將多行代碼用另一種方式寫成了一行代碼。

這并不意味著,代碼行數(shù)越少,就越 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 

建議還是按照如下的寫法來(lái)

  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 循環(huán)時(shí),如何取得對(duì)應(yīng)的索引,初學(xué)者習(xí)慣使用 range + len 函數(shù)

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

更好的做法是利用 enumerate 這個(gè)內(nèi)置函數(shù)

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

5. 序列解包

使用 * 可以對(duì)一個(gè)列表解包

  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. 字符串拼接

如果一個(gè)列表(或者可迭代對(duì)象)中的所有元素都是字符串對(duì)象,想要將他們連接起來(lái),通常做法是

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

更推薦的做法是使用 join 函數(shù)

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

7. 真假判斷

判斷一個(gè)變量是否為真(假),新手習(xí)慣直接使用 == 與 True、False、None 進(jìn)行對(duì)比

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

實(shí)際上,""、[]、{} 這些沒有任何元素的容器都是假值,可直接使用 if not xx 來(lái)判斷。

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

8. 訪問(wèn)字典元素

當(dāng)直接使用 [] 來(lái)訪問(wèn)字典里的元素時(shí),若key不存在,是會(huì)拋異常的,所以新會(huì)可能會(huì)先判斷一下是否有這個(gè) key,有再取之。

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

更推薦的做法是使用 get 來(lái)取,如果沒有該 key 會(huì)默認(rèn)返回 None(當(dāng)然你也可以設(shè)置默認(rèn)返回值)

  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. 操作列表

下面這段代碼,會(huì)根據(jù)條件過(guò)濾過(guò)列表中的元素

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

實(shí)際上可以使用列表推導(dǎo)或者高階函數(shù) filter 來(lái)實(shí)現(xiàn)

  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 這兩個(gè)函數(shù)也很好用

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

10. 文件讀取

文件讀取是非常常用的操作,在使用完句柄后,是需要手動(dòng)調(diào)用 close 函數(shù)來(lái)關(guān)閉句柄的

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

如果代碼寫得太長(zhǎng),即使你知道需要手動(dòng)關(guān)閉句柄,卻也會(huì)經(jīng)常會(huì)漏掉。因此推薦養(yǎng)成習(xí)慣使用 with open 來(lái)讀寫文件,上下文管理器會(huì)自動(dòng)執(zhí)行關(guān)閉句柄的操作

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

11. 代碼續(xù)行

將一個(gè)長(zhǎng)度較長(zhǎng)的字符串放在一行中,是很影響代碼可讀性的(下面代碼可向左滑動(dòng))

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

稍等注重代碼可讀性的人,會(huì)使用三個(gè)引號(hào) \來(lái)續(xù)寫

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

不過(guò),對(duì)我來(lái)說(shuō),我更喜歡這樣子寫 使用括號(hào)包裹 ()

  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.”" 

導(dǎo)包的時(shí)候亦是如此

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

12. 顯式代碼

有時(shí)候出于需要,我們會(huì)使用一些特殊的魔法來(lái)使代碼適應(yīng)更多的場(chǎng)景不確定性。

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

但若非必要,請(qǐng)不要那么做。無(wú)端增加代碼的不確定性,會(huì)讓原先本就動(dòng)態(tài)的語(yǔ)言寫出更加動(dòng)態(tài)的代碼。

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

13. 使用占位符

對(duì)于暫不需要,卻又不得不接收的的變量,請(qǐng)使用占位符

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

14. 鏈?zhǔn)奖容^

對(duì)于下面這種寫法

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

其實(shí)還有更好的寫法

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

如果你理解了上面的鏈?zhǔn)奖容^操作,那么你應(yīng)該知道為什么下面這行代碼輸出的結(jié)果是 False

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

15. 三目運(yùn)算

對(duì)于簡(jiǎn)單的判斷并賦值

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

其實(shí)是可以使用三目運(yùn)算,一行搞定。

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

 

責(zé)任編輯:趙寧寧 來(lái)源: Python編程時(shí)光
相關(guān)推薦

2017-07-27 16:18:18

開源項(xiàng)目使用

2017-09-08 12:15:54

Python代碼Pythonic

2022-02-17 07:54:55

VSCodeLinux內(nèi)核

2012-08-27 09:36:51

程序員創(chuàng)業(yè)讀書

2021-02-19 23:55:15

PythonPythonic數(shù)據(jù)

2021-02-05 11:36:42

數(shù)據(jù)業(yè)務(wù)指標(biāo)

2023-03-23 22:46:38

Spring限流機(jī)制

2021-04-20 10:50:38

Spring Boot代碼Java

2023-01-11 11:35:40

重構(gòu)PythonPythonic

2023-09-26 12:04:15

重構(gòu)技巧Pythonic

2023-02-06 12:00:00

重構(gòu)PythonPythonic

2016-11-09 20:21:12

簡(jiǎn)歷開源時(shí)間管理工具編程語(yǔ)言

2025-02-06 08:54:45

gockGoHTTP

2020-05-15 15:28:51

爬蟲Python學(xué)習(xí)

2022-04-24 08:23:19

Redis內(nèi)存淘汰策略

2022-08-19 14:24:30

forPythonpythonic

2015-09-21 09:38:14

營(yíng)銷H5

2017-09-14 12:03:30

大數(shù)據(jù)數(shù)據(jù)分析語(yǔ)言

2024-05-10 14:46:27

Pythonfor循環(huán)

2015-09-21 11:34:59

H5發(fā)展
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)