python有趣用法匯總(持續更新)

來源:互聯網
上載者:User

標籤:Python   職業   爬蟲   學習Python   

使用python過程中經常會不經意間遇到非常有趣的用法,於是特意搜集了一些

有趣的用法

1.for-else用法

迴圈正常結束則執行else語句。一般用於迴圈找合格元素,如果找到則break調出迴圈,不會觸發else;如果沒有找到(完整運行迴圈)則print not found

詳見Python中迴圈語句中的else用法

《Effictive Python》一書中對for-else用法提出了質疑,主要觀點是可以通過封裝成函數來取代這一用法,而封裝成函數是更加通用易懂的做法,所以一般不會使用for-else用法。為了不影響文章的緊湊,我把評論區對書上內容的引用放在文末“更新補充”部分,有興趣的讀者可以去看一下。

2.try-else用法

如果沒有觸發異常就執行else

參考這裡

3.解包用法

類似這樣a,b,c = [‘a‘, ‘b‘, ‘c‘]

python有趣的解包用法

4.單行if-else

a = 1b = 3 if a == 1 else 2print(‘it is one‘ if a == 1 else ‘no‘)

5.迭代器傳入函數中不用加括弧

# 一般是這樣a = (i for i in range(10))sum(a)# 我們可以這樣sum((i for i in range(10)))# 但我們還可以這樣sum(i for i in range(10))# 類似的有‘ ‘.join(str(i) for i in range(10))#加群:725479218 擷取更多的學習資料

6.對產生器進行篩選

一個素數產生器的例子

7.or的用法

python中x or y表示如果x為真就是x的值,否則為y的值

我們會經常看到類似這樣的用法(比如函數的一個value參數沒有設定預設值,這樣使用就允許它不賦值)

value = value or {}# 相當於value = value if value else {}

8.and的用法

python中x and y表示如果x是假,結果就是x的值,否則就是y的值

x and y and z多個and串連時,如果全是真結果就是最後一個的值;如果中間有假的值,結果就是第一個假的值

舉一個例子

def not_empty(a):    return a and a.strip()not_empty(‘ a ‘)# 值為 ‘a‘not_empty(None)# 不會報錯(如果 return a.strip() 就會報錯)# 在處理None的問題上相當於def not_empty(a):    if a is None:        return None    else:        return a.strip()#加群:725479218 擷取更多的學習資料

細細品味and和or的差別,他們邏輯類似,但是實現的功能是不可以相互替代的

  • or 是結果如果不滿意有個善後工作
  • and是要做一件事之前先檢驗一下,不能做就不讓它做

9.if value:

# 要用if value:# 不要用if value == True:

這裡總結一下這種情況下什麼時候是True,什麼時候是False

False: 0 0.0 ‘‘ [] {} () set() None False

True:

  • ‘ ‘ ‘anything‘ [‘‘] [0] (None, )
  • 沒有內容的可迭代對象

另外要注意一點,我們用if判斷一個對象是不是None的時候,要if a is None而不要直接if a,因為如果是後者,有非常多不是None的情況也會判定為False,比如Null 字元串、空列表等,為了精確指定None還是要用前者,這也是一種規範。

10.底線的特殊使用

python中底線是一種特殊的變數和符號,有一些特殊的用途

詳見python中底線的使用

11.文檔字串

python有一種獨一無二的注釋方式,在包、模組、函數、類中第一句,使用‘‘‘doc‘‘‘這樣三引號注釋,就可以在對象中用__doc__的方式提取

比較規範的寫法是這樣的(這裡參考grequests模組的寫法)

def myfun(a, b):    ‘‘‘add two numbers    :param a: one number    :param b: another number    :returns: a number    ‘‘‘    print(a + b)print(myfun.__doc__)# 結果為add two numbers    :param a: one number    :param b: another number    :returns: a number #加群:725479218 擷取更多的學習資料

其實參數還有其他的寫法,如numpy庫的寫法,可以看這裡

除此之外,函數注釋還有另一種方式,函數名可以直接調用某個參數的注釋,詳Python 的函數注釋

有用的函數

1.sum的本質

本質:sum(iterable, start=0)將可迭代對象使用+串連

所以sum([[1,2],[3,4]], [])返回結果為[1, 2, 3, 4]

2.range(start, stop[, step])

可以直接用for i in range(10, 0, -1)降序迴圈

3.enumerate迴圈索引

for index, item in enumerate([‘a‘, ‘b‘, ‘c‘]):    print(index, item)輸出:0 a1 b2 c

4.管道操作

func1(func2(func3(a)))寫成類似a %>% func3 %>% func2 %>% func1,清晰展示函數執行的順序,增強可讀性

python本身不帶有這樣的用法,只是一些庫提供了這樣的用法,比如pandas和syntax_sugar
參考stackoverflow上的這個回答

其他

另外,就是一些基礎的

  • 列表推導式
  • 裝飾器
  • 產生器
  • map reduce filter
  • 鏈式比較
  • 類的魔術方法

上面很多在廖雪峰python教程中都能找到

閱讀優秀的代碼也是提高編程水平的好方法,參考下面這個問題

初學 Python,有哪些 Pythonic 的源碼推薦閱讀?

學習代碼規範可以參考下面資料

  • PEP8
  • Python 代碼、單元測試和項目規範
  • google開源項目風格指南

更新補充

  1. for-else的更多討論

下面引用《Effictive Python》一書中內容
``
a = 4 b = 9

for i in range(2, min(a, b) + 1):
print(‘Testing‘, i)
if a % i == 0 and b % i == 0:
print(‘Not coprime‘)
break
else:
print(‘Coprime‘)
``
隨後作者寫到:

In practice, you wouldn’t write the code this way. Instead, you’d write a helper function to do the calculation. Such a helper function is written in two common styles.
The first approach is to return early when you find the condition you’re looking for. You return the default outcome if you fall through the loop.

def coprime(a, b):
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
return False
return True

The second way is to have a result variable that indicates whether you’ve found what you’re looking for in the loop. You break out of the loop as soon as you find something.

def coprime2(a, b):
is_coprime = True
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
is_coprime = False
break
return is_coprime

結尾:

Both of these approaches are so much clearer to readers of unfamiliar code. The expressivity you gain from the else block doesn’t outweigh the burden you put on people (including yourself) who want to understand your code in the future. Simple constructs like loops should be self-evident in Python. You should avoid using else blocks after loops entirely.

總結起來就是for-else的優勢是可以被寫函數的方式替代的

python有趣用法匯總(持續更新)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.