天天看點

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 = 
b =  
if a ==  
else 
print('it is one' if a ==  else 'no')
           

5.疊代器傳入函數中不用加括号

# 一般是這樣
a = (i for i in range())
sum(a)
# 我們可以這樣
sum((i for i in range()))
# 但我們還可以這樣
sum(i for i in range())
# 類似的有
' '.join(str(i) for i in range())
#加群: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

,比如空字元串、空清單等,為了精确指定

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)
輸出:
 a
 b
 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的優勢是可以被寫函數的方式替代的