有時候你會看到很Cool的Python代碼,你驚訝於它的簡潔,它的優雅,你不由自主地贊嘆:竟然還能這樣寫。其實,這些優雅的代碼都要歸功於Python的特性,只要你能掌握這些Pythonic的技巧,你一樣可以寫出像詩一樣的Python代碼。
1.導入模塊
你是不是經常對調用模塊時輸入一長串模塊索引感到頭疼?說實在的,數量少的時候或許還可以勉強忍受,一旦程序規模上去了,這也是一項不容小覷的工程。
#Bad
import urllib.request
url = r'http://www.landsblog.com'
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
#Good
form urllib import request
url = r'http://www.landsblog.com'
req = request.Request(url)
response = request.urlopen(req)
這樣是不是節省了一點時間呢?
但是這樣簡寫可能造成模塊名重復的問題,如何解決呢?
from module_a import fun as a_fun
from module_b import fun as b_fun
這樣的方法還適用於模塊名比較長的模塊,筆者印象最深的就是BeautifulSoup模塊
from bs4 import BeautifulSoup as BS
html = '''
<html>
......
</html>
'''
soup = BS(html)
省時省力。
2.關於 "_"
這是一個非常有用的功能,可惜很少人知道。
當你在交互界面敲代碼,獲得一個臨時結果,卻沒有用變量名去保存它的時候,可以用"_"來獲取最近一次臨時結果。
>>> 1 + 1
2
>>> _
2
在"_"中存儲最后輸出的值。這在交互式模式中是非常有用的,當你在過程中沒有保存計算結果,或者你想看最后一步執行的輸出結果。
3.合並字符串
這是一個老生常談的問題,當我們需要將數個字符串合並的時候,習慣性的使用"+"作為連接字符串的手段。
然而,由於不可變對象在內存中生成后無法修改,合並后的字符串會重新開辟出一塊內存空間來存儲。這樣像滾雪球一樣,將內存快速消耗殆盡。
# Bad
string = ['a','b','c','d','e','f','g','h']
def fun(string):
all_string = ''
for i in string:
all_string += i
return all_string
# Good
string = ['a','b','c','d','e','f','g,'h']
def fun(string):
all_string = ''.join(string)
return all_string
4.強大的zip()
它是Python的內建函數,zip函數接受任意多個(包括0個和1個)序列作為參數,返回一個包含tuple的list。zip()函數可以在很多場景簡化你的代碼。
矩陣的行列互換
# Bad
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
re_a = [[row[col] for row in a] for col in range(len(a))]
>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# Good
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
re_a = list(zip(*a))
>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
交換dict的鍵值
# Bad
a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
def reverse_dict(a):
new_dict = {}
for k,v in m.items():
new_dict[v] = k
return new_dict
# Good
a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
def reverse_dict(a):
k = a.keys()
v = a.values()
new_dict = dict(zip(v, k))
return new_dict
合並list相鄰項
a = [1, 2, 3, 4, 5, 6]
list(zip( a[::2], a[1::2] ))
>>> [(1, 2), (3, 4), (5, 6)]
5.變量值交換
# Bad
tmp = a
a = b
b = tmp
#Good
a, b = b, a
6.在循環中獲取索引(數組下標)?
a = [8, 23, 45, 12, 78]
for index, value in enumerate(a):
print(index , value)
7.如何在只用一行捕獲多個異常?
try:
pass
except (ExceptionA,ExceptionB,.....) as e:
pass
8.把列表分割成同樣大小的塊?
a = [1, 2, 3, 4, 5, 6]
list(zip( *[iter(a)]*2 ))
>>> [(1, 2), (3, 4), (5, 6)]
9.如何查找列表中某個元素的下標?
a = ['a', 'b', 'c', 'd', 'e', 'f']
a_i = a.index(a)
>>> 0
10.如何快速反轉字符串?
#Bad
a = 'Python is a powerful languange.'
list_a = list(a)
list_a.reverse()
re_a = ''.join(list_a)
#Good
a = 'Python is a powerful languange.'
re_a = a[::-1]
11.數值比較
x = 2
if 1< x <3:
print(x)
>>> 2
if 1< x >0:
print(x)
>>> 2
12.優雅的打開文件
平時在使用類似文件的流對象時,使用完畢后要調用close方法關閉。with…as語句提供了一個非常方便的替代方法:open打開文件后將返回的文件流對象賦值給f,然后在with語句塊中使用。with語句塊完畢之后,會隱藏地自動關閉文件。
with open('nothing.txt','r') as f:
f.read()
13.和你的內存說再見
crash = dict(zip(range(10 **0xA), range(10 **0xA)))
歡迎交流,轉載請注明出處~ (^ _ ^)/~~
更多Python相關技巧:http://www.landsblog.com/blog/