python有趣用法彙總
使用python過程中經常會不經意間遇到非常有趣的用法,於是特意蒐集了一些
有趣的用法
1.for-else用法
迴圈正常結束則執行else語句。一般用於迴圈找符合條件的元素,如果找到則break
調出迴圈,不會觸發else
;如果沒有找到(完整執行迴圈)則print not found
《Effictive Python》一書中對for-else用法提出了質疑,主要觀點是可以通過封裝成函式來取代這一用法,而封裝成函式是更加通用易懂的做法,所以一般不會使用for-else用法。
2.try-else用法
如果沒有觸發異常就執行else
參考這裡
3.解包用法
類似這樣a,b,c = ['a', 'b', 'c']
4.單行if-else
<pre class=" hljs bash language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;">a = 1
b = 3
if a == 1
else 2
print('it is one' if a == 1 else 'no')
</pre>
5.迭代器傳入函式中不用加括號
<pre class=" hljs bash language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;"># 一般是這樣
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))
</pre>
7.or的用法
python中x or y
表示如果x為真就是x的值,否則為y的值
我們會經常看到類似這樣的用法(比如函式的一個value
引數沒有設定預設值,這樣使用就允許它不賦值)
<pre class=" hljs php language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;">value = value or {}
相當於
value = value if value else {}
</pre>
8.and的用法
python中x and y
表示如果x是假,結果就是x的值,否則就是y的值
x and y and z
多個and連線時,如果全是真結果就是最後一個的值;如果中間有假的值,結果就是第一個假的值
舉一個例子
<pre class=" hljs python language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;">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()
</pre>
細細品味and和or的差別,他們邏輯類似,但是實現的功能是不可以相互替代的
- or 是結果如果不滿意有個善後工作
- and是要做一件事之前先檢驗一下,不能做就不讓它做
9.if value:
<pre class=" hljs php language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;"># 要用
if value:
不要用
if value == True:
</pre>
這裡總結一下這種情況下什麼時候是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中下劃線是一種特殊的變數和符號,有一些特殊的用途
11.文件字串
python有一種獨一無二的註釋方式,在包、模組、函式、類中第一句,使用'''doc'''
這樣三引號註釋,就可以在物件中用__doc__
的方式提取
比較規範的寫法是這樣的(這裡參考grequests
模組的寫法)
<pre class=" hljs python language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;">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
</pre>
其實引數還有其他的寫法,如numpy
庫的寫法,可以看這裡
除此之外,函式註釋還有另一種方式,函式名可以直接呼叫某個引數的註釋,詳見Python 的函式註釋 。還可以參考PEP 257
有用的函式
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迴圈索引
<pre class=" hljs bash language-python" style="border: 1px solid rgba(0, 0, 0, 0.0980392); font-size: 15px; font-style: normal; font-weight: normal; margin: 1em 2em; outline: 0px; padding: 1em; vertical-align: baseline; font-family: Consolas, Monaco, "andale mono", "ubuntu mono", monospace; background: rgb(245, 242, 240); color: rgb(0, 0, 0); hyphens: none; line-height: 1.5; box-sizing: border-box; max-width: 100%; overflow: auto; white-space: pre; word-wrap: normal; max-height: 500px; text-shadow: rgb(255, 255, 255) 0px 1px; text-align: left; word-spacing: 0px; word-break: normal; tab-size: 4; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: 0.5px; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; -webkit-text-stroke-width: 0px;">for index, item in enumerate(['a', 'b', 'c']):
print(index, item)
輸出:
0 a
1 b
2 c
</pre>
4.管道操作
func1(func2(func3(a)))寫成類似a %>% func3 %>% func2 %>% func1,清晰展示函式執行的順序,增強可讀性
python本身不帶有這樣的用法,只是一些庫提供了這樣的用法,比如pandas和syntax_sugar
其他
另外,就是一些基礎的
- 列表推導式
- 裝飾器
- 生成器
-
map reduce filter
- 鏈式比較
- 類的魔術方法