python語言-pep8使用技巧
Python由於語言的簡潔性,讓我們以人類思考的方式來寫程式碼,新手更容易上手,老鳥更愛不釋手。
要寫出 Pythonic(優雅的、地道的、整潔的)程式碼,還要平時多觀察那些大牛程式碼,Github 上有很多非常優秀的原始碼值得閱讀,比如:requests、flask、tornado,這裡小明收集了一些常見的 Pythonic 寫法,幫助你養成寫優秀程式碼的習慣。
python技巧
序列解包
a, *rest = [1, 2, 3] # a = 1, rest = [2, 3] a, *middle, c = [1, 2, 3, 4] # a = 1, middle = [2, 3], c = 4
遍歷列表以及索引
##不推薦 items = 'zero one two three'.split() # method 1 i = 0 for item in items: print i, item i += 1 # method 2 for i in range(len(items)): print i, items[i] ##推薦 items = 'zero one two three'.split() for i, item in enumerate(items): print i, item
字典get和setdefault方法
##不推薦 navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs[portfolio] = 0 navs[portfolio] += position * prices[equity] ##推薦 navs = {} for (portfolio, equity, position) in data: # 使用 get 方法 navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity] # 或者使用 setdefault 方法 navs.setdefault(portfolio, 0) navs[portfolio] += position * prices[equity]
遍歷列表以及索引
##不推薦 items = 'zero one two three'.split() # method 1 i = 0 for item in items: print i, item i += 1 # method 2 for i in range(len(items)): print i, items[i] ##推薦 items = 'zero one two three'.split() for i, item in enumerate(items): print i, item
列表推導-巢狀
##不推薦 for sub_list in nested_list: if list_condition(sub_list): for item in sub_list: if item_condition(item): # do something... ##推薦 gen = (item for sl in nested_list if list_condition(sl) for item in sl if item_condition(item)) for item in gen: # do something...
迴圈巢狀
##不推薦 for x in x_list: for y in y_list: for z in z_list: # do something for x & y ##推薦 from itertools import product for x, y, z in product(x_list, y_list, z_list): # do something for x, y, z
中間結果儘量使用imap/ifilter代替map/filte
##不推薦 reduce(rf, filter(ff, map(mf, a_list))) ##推薦 from itertools import ifilter, imap reduce(rf, ifilter(ff, imap(mf, a_list))) *lazy evaluation 會帶來更高的記憶體使用效率,特別是當處理大資料操作的時候。
使用any/all函式
##不推薦 found = False for item in a_list: if condition(item): found = True break if found: # do something if found... ##推薦 if any(condition(item) for item in a_list): # do something if found...
屬性(property)
##不推薦 class Clock(object): def __init__(self): self.__hour = 1 def setHour(self, hour): if 25 > hour > 0: self.__hour = hour else: raise BadHourException def getHour(self): return self.__hour ##推薦 class Clock(object): def __init__(self): self.__hour = 1 def __setHour(self, hour): if 25 > hour > 0: self.__hour = hour else: raise BadHourException def __getHour(self): return self.__hour hour = property(__getHour, __setHour)
使用 with 忽視異常(僅限Python 3)
##不推薦 try: os.remove("somefile.txt") except OSError: pass ##推薦 from contextlib import ignored# Python 3 only with ignored(OSError): os.remove("somefile.txt")
使用 with 處理加鎖
##不推薦 import threading lock = threading.Lock() lock.acquire() try: # 互斥操作... finally: lock.release() ##推薦 import threading lock = threading.Lock() with lock: # 互斥操作...
使用佔位符
filename = 'foobar.txt' basename, _, ext = filename.rpartition('.')
鏈式比較
# 不推薦 if age > 18 and age < 60: print("young man") # 推薦 if 18 < age < 60: print("young man") >>> False == False == True False
<.>
和<.?>
有什麼區別
<.>
這種匹配稱作貪心匹配<.?>
稱作非貪心匹配
Python裡面search()和match()的區別
match()函式只檢測RE是不是在string的開始位置匹配, search()會掃描整個string查詢匹配, 也就是說match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none
如何用Python來進行查詢和替換一個文字字串?
可以使用sub()
方法來進行查詢和替換,sub方法的格式為:sub(replacement, string[, count=0])
- replacement是被替換成的文字
- string是需要被替換的文字
- count是一個可選引數,指最大被替換的數量
import re p = re.compile(’(blue|white|red)’) print(p.sub(’colour’,'blue socks and red shoes’)) print(p.sub(’colour’,'blue socks and red shoes’, count=1))
subn()方法執行的效果跟sub()一樣,不過它會返回一個二維陣列,包括替換後的新的字串和總共替換的數量
import re p = re.compile(’(blue|white|red)’) print(p.subn(’colour’,'blue socks and red shoes’)) print(p.subn(’colour’,'blue socks and red shoes’, count=1))
有兩個序列a,b,大小都為n,序列元素的值任意整形數
無序;要求:通過交換a,b中的元素,使[序列a元素的和]與[序列b元素的和]之間的差最小。
將兩序列合併為一個序列,並排序,為序列Source
拿出最大元素Big,次大的元素Small
在餘下的序列S[:-2]進行平分,得到序列max,min
將Small加到max序列,將Big加大min序列,重新計算新序列和,和大的為max,小的為min。
def mean( sorted_list ): if not sorted_list: return (([],[])) big = sorted_list[-1] small = sorted_list[-2] big_list, small_list = mean(sorted_list[:-2]) big_list.append(small) small_list.append(big) big_list_sum = sum(big_list) small_list_sum = sum(small_list) if big_list_sum > small_list_sum: return ( (big_list, small_list)) else: return (( small_list, big_list)) tests = [[1,2,3,4,5,6,700,800], [10001,10000,100,90,50,1], range(1, 11), [12312, 12311, 232, 210, 30, 29, 3, 2, 1, 1] ] for l in tests: l.sort() print print “Source List:”, l l1,l2 = mean(l) print “Result List:”, l1, l2 print “Distance:”, abs(sum(l1)-sum(l2)) print ‘-*’*40