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

30個Python優(yōu)秀實踐和技巧,你值得擁有~

開發(fā) 后端
官方宣布自2020年1月一日起將不再支持Python2。這份指南里的大多數(shù)例子也只在Python3中適用。如果您還在使用Python2.7,趕快更新吧。如果您使用的是蘋果電腦,可以使用Homebrew輕松升級。

 1. 使用Python3

溫馨提示:官方宣布自2020年1月一日起將不再支持Python2。這份指南里的大多數(shù)例子也只在Python3中適用。如果您還在使用Python2.7,趕快更新吧。如果您使用的是蘋果電腦,可以使用Homebrew輕松升級。

[[313775]]

2. 檢查Python的最低要求版本

您可以直接使用代碼來查看Python版本,確保將來不會出現(xiàn)腳本和Python版本不兼容的情況發(fā)生。請看示例:

  1. ifnot  sys.version_info > (2, 7): 
  2.  
  3.    # berate your user for running a  10 year 
  4.  
  5.    # python version 
  6.  
  7. elifnot  sys.version_info >= (3, 5): 
  8.  
  9.    # Kindly tell your user (s)he  needs to upgrade 
  10.  
  11.    # because you're using 3.5  features 

viewrawcheck_python_version.py hosted with ❤ by GitHub

3. 使用IPython

 

作者截圖

實際上,IPython是一個增強的shell。自動完成功能已足以令人驚嘆,但它還有更多功能。我非常喜歡內(nèi)置的魔術(shù)命令。以下是一些例子:

  • %cd -用于更改當前工作目錄
  • 編輯-打開編輯器,并執(zhí)行您在關(guān)閉編輯器后鍵入的代碼
  • %env — 展示當前環(huán)境變量
  • %pip install [pkgs] — 在交互環(huán)境下安裝包
  • %time 和 %timeit — 計算Python代碼的執(zhí)行時間

另一個有用的功能是引用前一個命令的輸出。In和Out是實際的對象。您可以通過使用Out[3]來進行第三個命令的輸出。

下載Python命令安裝Ipython:

  1. pip3install ipython 

4. 列表推導

列表推導可以替換丑陋的用于填充列表的for循環(huán)。列表推導的基本語法是:

  1. [expression for item in list if conditional ] 

這是一個最基本的例子,使用數(shù)字序列填充列表:

  1. mylist = [i for i inrange(10)] 
  2.  
  3. print(mylist) 
  4.  
  5. # [0, 1,  2, 3, 4, 5, 6, 7, 8, 9] 

viewrawlist_comprehensions_1.py hostedwith ❤ by GitHub

同時你還可以用這種表達進行數(shù)學運算:

  1. squares = [x**2for x inrange(10)] 
  2.  
  3. print(squares) 
  4.  
  5. # [0, 1,  4, 9, 16, 25, 36, 49, 64, 81] 

viewrawlist_comprehensions_2.py hostedwith ❤ by GitHub

甚至額外創(chuàng)建一個新函數(shù):

  1. defsome_function(a): 
  2.  
  3.     return (a +5) /2 
  4.  
  5. my_formula  = [some_function(i) for i inrange(10)] 
  6.  
  7. print(my_formula) 
  8.  
  9. # [2, 3,  3, 4, 4, 5, 5, 6, 6, 7] 

viewrawlist_comprehensions_3.py hostedwith ❤ by GitHub

最終,你可以使用“if”來過濾列表。在這個例子中,只保留了能被2整除的值

  1. filtered  = [i for i inrange(20) if i%2==0] 
  2.  
  3. print(filtered) 
  4.  
  5. # [0, 2,  4, 6, 8, 10, 12, 14, 16, 18] 

viewrawlist_comprehensions_4.py hosted with ❤ by GitHub

5.檢查對象的內(nèi)存使用

使用 sys.getsizeof(),可以檢查對象的記憶內(nèi)存:

  1. import sys 
  2.  
  3. mylist =range(0, 10000) 
  4.  
  5. print(sys.getsizeof(mylist)) 
  6.  
  7. # 48 

viewrawcheck_memory_usage_1.py hostedwith ❤ by GitHub

為什么這樣一個巨大的列表僅占48字節(jié)內(nèi)存? 這是因為range函數(shù)返回的類只表現(xiàn)為一個列表。范圍比使用實際的數(shù)字列表更節(jié)省內(nèi)存。 你可以自己使用列表推導創(chuàng)建同一范圍內(nèi)的實際數(shù)字列表:

  1. import sys 
  2.  
  3. myreallist  = [x for x inrange(0, 10000)] 
  4.  
  5. print(sys.getsizeof(myreallist)) 
  6.  
  7. # 87632 

viewrawcheck_memory_usage_2.py hosted with ❤ by GitHub

6. 返回多個值

Python中的函數(shù)可以返回多個變量,而無需字典、列表或類。它的工作原理如下:

  1. defget_user(id): 
  2.  
  3.     # fetch user from database 
  4.  
  5.     # .... 
  6.  
  7.     return name,  birthdate 
  8.  
  9. name,  birthdate = get_user(4) 

viewrawreturn_multiple_variables.py hosted with ❤ by GitHub

對于有限數(shù)量的返回值,這是可以的。但是任何超過3個值的內(nèi)容都應(yīng)該放到一個(data)類中。

7. 使用數(shù)據(jù)類

從3.7版開始,Python提供了數(shù)據(jù)類。與常規(guī)類或其他替代方法(如返回多個值或字典)相比,有幾個優(yōu)點:

  • 一個數(shù)據(jù)類需要最少的代碼
  • 可以比較數(shù)據(jù)類,因為已經(jīng)實現(xiàn)了_eq__
  • 您以輕易打印一個數(shù)據(jù)類進行調(diào)試,因為也實現(xiàn)了_repr__
  • 數(shù)據(jù)類需要類型提示,減少了出錯幾率 下面是一個數(shù)據(jù)類的例子:
  1. from  dataclasses import dataclass 
  2.  
  3. @dataclass 
  4.  
  5. classCard: 
  6.  
  7.     rank: str 
  8.  
  9.     suit: str 
  10.  
  11. card = Card("Q""hearts"
  12.  
  13. print(card == card) 
  14.  
  15. True 
  16.  
  17. print(card.rank) 
  18.  
  19. 'Q' 
  20.  
  21. print(card) 
  22.  
  23. Card(rank='Q', suit='hearts' 

viewrawdataclass.py hosted with ❤ by GitHub

點擊這里查看高階指南 。

8. 變量交換

一個小技巧就可以省略數(shù)行代碼。

  1. a =1 
  2.  
  3. b =2 
  4.  
  5. a, b = b, a 
  6.  
  7. print (a) 
  8.  
  9. # 2 
  10.  
  11. print (b) 
  12.  
  13. # 1 

viewrawin_place_variable_swapping.py hosted with ❤ by GitHub

9. 合并字典(Python3.5+)

自Python3.5 以來,合并字典更為簡便

  1. dict1 = { 'a': 1, 'b': 2 } 
  2.  
  3. dict2 = { 'b': 3, 'c': 4 } 
  4.  
  5. merged = { **dict1, **dict2 } 
  6.  
  7. print  (merged) 
  8.  
  9. # {'a':  1, 'b': 3, 'c': 4} 

viewrawmerging_dicts.py hostedwith ❤ by GitHub

如果有重疊的值,來自第一個字典的值將被覆蓋。

10. 標題大小寫

這只是其中一種有趣的玩法:

  1. mystring  ="10  awesome python tricks" 
  2.  
  3. print(mystring.title()) 
  4.  
  5. '10  Awesome Python Tricks' 

viewrawstring_to_titlecase.py hosted with ❤ by GitHub

11. 切割字符串至列表

可以將字符串拆分為字符串列表。在下例中,根據(jù)空格切割

  1. mystring  ="The  quick brown fox" 
  2.  
  3. mylist =  mystring.split(' '
  4.  
  5. print(mylist) 
  6.  
  7. #  ['The''quick''brown''fox'

viewrawstring_to_list.py hosted with ❤ by GitHub

12. 從字符串列表中創(chuàng)建一個字符串

與上一個技巧正好相反,在本例中,從字符串列表中創(chuàng)建一個字符串,并在單詞間輸入空格:

  1. mylist = ['The''quick''brown''fox'
  2.  
  3. mystring  ="  ".join(mylist) 
  4.  
  5. print(mystring) 
  6.  
  7. 'The  quick brown fox' 

viewrawlist_to_string.py hostedwith ❤ by GitHub

你或許在想為什么不用mylist.join(" ") ,好問題!

歸根結(jié)底,String.join()函數(shù)不僅可以連接列表,還可以連接任何可迭代的列表。將它放在String中會阻止在多個位置實現(xiàn)相同的功能。

13. 表情

表情要么是歡喜,要么是討厭,這依表情而定。更重要的是,這在分析社交媒體數(shù)據(jù)時尤其有用。 首先,下載表情模塊

  1. pip3install emoji 

下載完之后,就可以按如下操作:

  1. import emoji 
  2.  
  3. result =  emoji.emojize('Python is :thumbs_up:'
  4.  
  5. print(result) 
  6.  
  7. #  'Python is 👍' 
  8.  
  9. # You  can also reverse this: 
  10.  
  11. result =  emoji.demojize('Python is 👍'
  12.  
  13. print(result) 
  14.  
  15. #  'Python is :thumbs_up:' 

viewrawemoji.py hosted with ❤ by GitHub

14. 制作列表切片

列表切片的句法:

  1. a[start:stop:step] 

Start, stop 和 step 都是可選項. 如果未設(shè)置,默認值會是

  • Start值為0
  • End為字符串末尾
  • step值為1

以下是一個例子:

  1. # We can  easily create a new list from 
  2.  
  3. # the  first two elements of a list: 
  4.  
  5. first_two  = [1, 2, 3, 4, 5][0:2] 
  6.  
  7. print(first_two) 
  8.  
  9. # [1, 2] 
  10.  
  11. And if  we use a step value of 2, 
  12.  
  13. # we can  skip over every second number 
  14.  
  15. like  this: 
  16.  
  17. steps = [1, 2, 3, 4, 5][0:5:2] 
  18.  
  19. print(steps) 
  20.  
  21. # [1, 3,  5] 
  22.  
  23. # This  works on strings too. In Python, 
  24.  
  25. # you  can treat a string like a list of 
  26.  
  27. #  letters: 
  28.  
  29. mystring  ="abcdefdn  nimt"[::2] 
  30.  
  31. print(mystring) 
  32.  
  33. 'aced  it' 

viewrawlist_slicing.py hosted with ❤ by GitHub

15. 反轉(zhuǎn)字符串和列表

使用上面的切片符號來反轉(zhuǎn)字符串或列表。通過使用負的步進值-1,從而反轉(zhuǎn)元素:

  1. revstring  ="abcdefg"[::-1] 
  2.  
  3. print(revstring) 
  4.  
  5. #  'gfedcba' 
  6.  
  7. revarray  = [1, 2, 3, 4, 5][::-1] 
  8.  
  9. print(revarray) 
  10.  
  11. # [5, 4,  3, 2, 1] 

viewrawreversing_stuff.py hosted with ❤ by GitHub

16. 展示小貓

首先,安裝Pillow(Python圖像庫的一個分支):

  1. pip3install Pillow 

下載這張圖片,并把它命名為kittens.jpg:

[[313776]] 

圖源 TheDigitalArtist Pixabay

可以使用以下代碼來顯示Python代碼中的圖像: 或者直接使用IPython:

  1. fromPILimport Image 
  2.  
  3. im =  Image.open("kittens.jpg"
  4.  
  5. im.show() 
  6.  
  7. print(im.format,  im.size, im.mode) 
  8.  
  9. # JPEG  (1920, 1357) RGB 

viewrawpillow.py hosted with ❤ by GitHub

除了顯示圖像,Pillow還可以分析、調(diào)整大小、過濾、增強、變形等等。有關(guān)它的所有特性,請參閱文檔。

17. 使用map()

Python的一個內(nèi)置函數(shù)是map()。map()的語法是: map(function, something_iterable) 給定一個要執(zhí)行的函數(shù),和一些要運行的變量。它可以是任何可迭代的元素。在下面的例子中,我將使用一個列表。

  1. defupper(s): 
  2.  
  3.     return  s.upper() 
  4.  
  5. mylist =list(map(upper,  ['sentence''fragment'])) 
  6.  
  7. print(mylist) 
  8.  
  9. #  ['SENTENCE''FRAGMENT'
  10.  
  11. #  Convert a string representation of 
  12.  
  13. # a  number into a list of ints. 
  14.  
  15. list_of_ints  =list(map(int"1234567"))) 
  16.  
  17. print(list_of_ints) 
  18.  
  19. # [1, 2,  3, 4, 5, 6, 7] 

viewrawmap.py hostedwith ❤ by GitHub

看看自己的代碼,看看是否可以在某處使用map()而不是循環(huán)!

18. 從列表和字符串中提取獨特元素

通過使用set()函數(shù)創(chuàng)建一個集合,可以從一個列表或類似列表的對象中獲得所有獨特的元素:

  1. mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6] 
  2.  
  3. print (set(mylist)) 
  4.  
  5. # {1, 2,  3, 4, 5, 6} 
  6.  
  7. And  since a string can be treated like a 
  8.  
  9. # list  of letters, you can also get the 
  10.  
  11. unique  letters from a string this way: 
  12.  
  13. print (set("aaabbbcccdddeeefff")) 
  14.  
  15. # {'a',  'b''c''d''e''f'

viewrawset.py hosted with ❤ by GitHub

19. 找到頻率出現(xiàn)最高的值

查找列表或字符串中最常出現(xiàn)的值:

  1. test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] 
  2.  
  3. print(max(set(test), key=  test.count)) 
  4.  
  5. # 4 

viewrawmost_frequent.py hostedwith ❤ by GitHub

你明白為什么會這樣嗎?在繼續(xù)閱讀之前,試著自己找出答案。還沒嘗試嗎?我要告訴你答案了。

  • max()將返回列表中的最大值。key參數(shù)接受單個參數(shù)函數(shù)來定制排序順序,在本例中,它是test.count。該函數(shù)應(yīng)用于iterable上的每個項目。
  • 測試。count是一個內(nèi)置的列表函數(shù)。它接受一個參數(shù),并將計算該參數(shù)的出現(xiàn)次數(shù)。因此test.count(1)將返回2,而test.count(4)將返回4。
  • set(test)返回test中所有的唯一值,因此{1,2,3,4} 因此,我們在這一行代碼中所做的就是獲取test的所有唯一值,即{1,2,3,4}。接下來,max將應(yīng)用list.count 函數(shù),并返回最大值。

20. 創(chuàng)建一個進度條

創(chuàng)建自己的進度條,這很有趣。但是使用進度包更快:

  1. pip3install progress 

現(xiàn)在可以花費更少的時間創(chuàng)建進度條

  1. from  progress.bar import Bar 
  2.  
  3. bar = Bar('Processing'max=20) 
  4.  
  5. for i inrange(20): 
  6.  
  7.     # Do some work 
  8.  
  9.     bar.next() 
  10.  
  11. bar.finish() 

viewrawprogress_bar.py hostedwith ❤ by GitHub

21. 在交互式窗口中使用_

可以用下劃線運算符得到最后一個表達式的結(jié)果,例如,在IPython中,如下所示:

  1. In [1]:3 * 3 
  2. Out[1]: 9In [2]: _ + 3 
  3. Out[2]: 12 

這也適用于Pythonshell。此外,IPython shell允許使用Out[n]來獲取[n]中的表達式的值。例如,Out[1]會給出數(shù)字9。

22. 快速創(chuàng)建一個web服務(wù)器

快速啟動web服務(wù)器,提供當前目錄的內(nèi)容:

  1. python3-m http.server 

如果您想與同事共享一些內(nèi)容,或者想測試一個簡單的HTML站點,這是非常有用的。

23. 多行字符串

盡管可以在代碼中使用三引號將多行字符串包括在內(nèi),但這并不理想。放在三引號之間的所有內(nèi)容都將成為字符串,包括格式,如下所示。

我更喜歡第二種方法,該方法將多行連接在一起,使您可以很好地格式化代碼。唯一的缺點是您需要顯式添加換行符。

  1. s1 ="""Multi  line strings can be put 
  2.  
  3.         between triple quotes. It's not ideal 
  4.  
  5.         when formatting your code  though""
  6.  
  7. print (s1) 
  8.  
  9. # Multi  line strings can be put 
  10.  
  11. #         between triple quotes. It's not  ideal 
  12.  
  13. #         when formatting your code though 
  14.  
  15. s2 = ("You  can also concatenate multiple\n"
  16.  
  17.         "strings  this way, but you'll have to\n" 
  18.  
  19.         "explicitly  put in the newlines"
  20.  
  21. print(s2) 
  22.  
  23. # You  can also concatenate multiple 
  24.  
  25. #  strings this way, but you'll have to 
  26.  
  27. #  explicitly put in the newlines 

viewrawmultiline_strings.py hosted with ❤ by GitHub

24.三元運算符,用于條件賦值

這是使代碼兼具簡潔性與可讀性的另一種方法:[on_true] if [expression] else[on_false] 例子:

  1. x = "Success!" if (y== 2) else "Failed!" 

25. 計算頻率

使用集合庫中的Counter來獲取包含列表中所有唯一元素計數(shù)的字典:

  1. from  collections import Counter 
  2.  
  3. mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6] 
  4.  
  5. c =  Counter(mylist) 
  6.  
  7. print(c) 
  8.  
  9. #  Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2}) 
  10.  
  11. And it  works on strings too: 
  12.  
  13. print(Counter("aaaaabbbbbccccc")) 
  14.  
  15. #  Counter({'a': 5, 'b': 5, 'c': 5}) 

viewrawcounter.py hosted with ❤ by GitHub

26. 鏈接比較運算符

在Python中鏈接比較運算符,以創(chuàng)建更易讀和簡潔的代碼:

  1. x =10 
  2.  
  3. #  Instead of
  4.  
  5. if x >5and x <15: 
  6.  
  7.     print("Yes"
  8.  
  9. # yes 
  10.  
  11. # You  can also write: 
  12.  
  13. if5< x <15: 
  14.  
  15.     print("Yes"
  16.  
  17. # Yes 

viewrawchaining_comparisons.py hosted with ❤ by GitHub

27. 添加一些顏色

使用Colorama,在終端添加點顏色.

  1. from  colorama import Fore, Back, Style 
  2.  
  3. print(Fore.RED+'some  red text'
  4.  
  5. print(Back.GREEN+'and  with a green background'
  6.  
  7. print(Style.DIM+'and in  dim text'
  8.  
  9. print(Style.RESET_ALL) 
  10.  
  11. print('back to  normal now'

viewrawcolorama.py hosted with ❤ by GitHub

28. 添加日期

python-dateutil模塊提供了對標準datetime模塊的強大擴展。 通過以下方式安裝:

  1. pip3 install python-dateutil 

您可以使用此庫做很多很棒的事情。我只會重點介紹對我來說特別有用的例子:如模糊分析日志文件中的日期等。

  1. from  dateutil.parser import parse 
  2.  
  3. logline ='INFO  2020-01-01T00:00:01 Happy new year, human.' 
  4.  
  5. timestamp  = parse(log_line, fuzzy=True
  6.  
  7. print(timestamp
  8.  
  9. #  2020-01-01 00:00:01 

viewrawdateutil.py hosted with ❤ by GitHub

只需記?。撼R?guī)的Python日期時間功能不奏效時,python-dateutil就派上用場了!

29. 整數(shù)除法

在Python 2中,除法運算符(/)默認為整數(shù)除法,除非操作數(shù)之一是浮點數(shù)。因此,有以下操作:

  1. # Python 2 
  2. 5 / 2 = 2 
  3. 5 / 2.0 = 2.5 

在Python 3中,除法運算符默認為浮點除法,并且//運算符已成為整數(shù)除法。這樣我們得到:

  1. Python 3 
  2. 5 / 2 = 2.5 
  3. 5 // 2 = 2 

30. 使用chardet進行字符集檢測

使用chardet模塊來檢測文件的字符集。在分析大量隨機文本時,這很有用。

安裝方式:

  1. pip install chardet 

現(xiàn)在,有了一個名為chardetect的額外命令行工具,可以像這樣使用:

  1. chardetect somefile.txt 
  2. somefile.txt: ascii with confidence 1.0 

以上就是2020年30條優(yōu)秀的代碼技巧。我希望您能像享受創(chuàng)建列表一樣,享受這些內(nèi)容。

 

責任編輯:華軒 來源: 讀芯術(shù)
相關(guān)推薦

2021-01-21 09:45:16

Python字符串代碼

2020-03-01 14:57:47

Python編程函數(shù)

2022-11-28 23:48:06

JavaScript編程語言技巧

2021-03-18 07:52:42

代碼性能技巧開發(fā)

2024-01-04 08:33:11

異步JDK數(shù)據(jù)結(jié)構(gòu)

2016-07-28 09:37:30

開源協(xié)作軟件Collabtive

2021-09-06 10:22:47

匿名對象編程

2020-12-14 13:32:40

Python進度條參數(shù)

2020-05-09 08:58:53

插件Android Stu開發(fā)工具

2014-12-19 10:55:17

Linux性能監(jiān)控

2020-09-01 07:41:56

macOS工具

2023-12-29 08:17:26

Python代碼分析Profile

2019-07-31 10:00:26

Github后臺控制面板框架

2023-03-01 07:57:38

PythonAI編程語言

2020-03-08 13:24:47

JavaScript開發(fā)

2022-01-18 16:42:03

區(qū)塊鏈加密信息資源

2025-01-06 08:00:00

Python代碼編程

2020-09-16 14:39:13

ReactJavaScript框架

2025-01-26 08:30:00

Python代碼編程

2025-04-03 08:25:26

點贊
收藏

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