value= true-expr if condition else false-exprpython
例如:a='positive' if 3>0 else 'negative'編程
a=[1,2,3,4,5] squares=list(map(lambda x:x**2,a)) print(squares) #[1, 4, 9, 16, 25] squares=[x**2 for x in a] print(squares) #[1, 4, 9, 16, 25] data=list(map(lambda x:x**2 ,filter(lambda x:x%2==0,a))) print(data) #[4, 16] data_one=[x**2 for x in a if x%2==0] 等價於data_one=[x**2 for x in a and x%2==0]
print(data_one) #[4, 16] #字典與集合也有相似的推導機制 chile_ranks={'ghost':1,'habanero':2,'cayenne':3} rank_dict={rank:name for name,rank in chile_ranks.items()} chile_len_set={len(name) for name in rank_dict.values()} print(rank_dict) #{1: 'ghost', 2: 'habanero', 3: 'cayenne'} print(chile_len_set) #{8, 5, 7}
能接收其餘函數做爲參數的函數,被稱爲高階函數(high-order function)app
表明性高階函數:map() filter() 和 reduce()函數式編程
map()函數接收兩個參數,一個是函數,一個是Iterable,map將傳入的函數依次做用到序列的每一個元素,函數
並把結果做爲新的Iterable返回。學習
lambda_sum=lambda x,y:x+y print(lambda_sum(3,4)) #7
data_list=[1,3,5,6] result=map(lambda x:x+3,data_list) print(list(result)) #[4, 6, 8, 9]
def f(x): return x+3 result_one=list(map(f,data_list)) print(result_one) #[4, 6, 8, 9]
reduce():把一個函數做用在一個序列[x1,x2,x3,...]上,這個函數必須接收兩個參數,reduce把結果url
繼續和序列的下一個元素作累積計算。感受用處不大!本身也能寫,會麻煩一些,若是須要,仍是可用。spa
from functools import reduce data_list=[1,3,5] print(reduce(lambda x,y:2*x+y,data_list)) #15
def f_reduce(x,y): return 2*x+y print(reduce(f_reduce,data_list)) #15
new_list=data_list[:1] for i in range(1,len(data_list)): new_list.append(2*new_list[i-1]+data_list[i]) print(new_list) #[1, 5, 15]
print(new_list[-1]) #15
def prod(L): new_list=L[:1] for i in range(1,len(L)): new_list.append(new_list[i-1]*L[i]) return new_list[-1] print(prod([3, 5, 7, 9])) #945
def prod(L): return reduce(lambda x,y:x*y,L) print(prod([3, 5, 7, 9])) #945
三、filter() ,和map()相似,也接收一個函數和一個序列。和map()不一樣的是,filter()把傳入的函數依次做用於每一個元素,code
而後根據返回值是True仍是False決定保留仍是丟棄該元素orm
list(filter(lambda x:x%2==0,[3,4,5])) #[4]
list(filter(lambda x:x%2==1,[3,4,5])) #[3,5]
lst=[x**2 for x in range(10)] #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
x1=[1,3,5] y1=[9,12,13] lst1=[x**2 for (x,y) in zip(x1,y1) if y>10] print(lst1) #[9, 25]
dict={k:v for k,v in enumerate('vamei') if v not in 'vi'} print(dict) #{1: 'a', 2: 'm', 3: 'e'}
import os,time,sys,requests POP20_CC=('CN IN US ID BR PK NG BD RU JP ' 'MX PH VN ET EG DE IR TR CD FR').split() BASE_URL='http://flupy.org/data/flags' DEST_DIR='E://' def save_flag(img,filename): path=os.path.join(DEST_DIR,filename) with open(path,'wb') as fp: fp.write(img) def get_flag(cc): url='{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower()) resp=requests.get(url) return resp.content def show(text): print(text,end=' ') sys.stdout.flush() def download_many(cc_list): for cc in sorted(cc_list): image=get_flag(cc) show(cc) save_flag(image,cc.lower()+'.gif') return len(cc_list) def main(download_many): t0=time.time() count=download_many(POP20_CC) elapsed=time.time()-t0 msg='\n{} flags downloaded in {:.2f}' print(msg.format(count,elapsed)) if __name__=='__main__': main(download_many)
簡單的一個代碼,寫的比較好!將一個腳本任務按照實現流程分爲幾個動做,每一個動做寫一個函數,有以下優勢:
一、代碼清晰
思路清晰,而非鬍子眉毛一把抓,總體任務分爲若干個小動做,一個動做用一個函數來實現。
二、易於擴展
若是代碼某一塊須要修改,能夠僅修改部分函數便可,對其餘函數無影響,也能夠增長其餘功能。
三、寫主函數
代碼中包含有主函數,從主函數開始,便於程序的閱讀,一看到main(),知道從這裏開始閱讀起。
四、不一樣函數之間變量名稱
寫函數的時候能夠以變量名稱、類型方式寫,注意函數內變量一致便可,調用時則使用全局變量中名稱,二者要不同嗎?爲何呢??
好比這樣改寫download_many函數:
for cc in sorted(POP20_CC):
image=get_flag(cc)
show(cc)
save_flag(image,cc.lower()+'.gif')
return len(POP20_CC)
若是咱們修改主函數,下載10個國家國旗圖片
def main(download_many):
t0=time.time()
count=download_many(POP10_CC)
elapsed=time.time()-t0
msg='\n{} flags downloaded in {:.2f}'
print(msg.format(count,elapsed))
結果是主函數的修改對download_many函數仍是起做用,由於download_many函數中變量只是至關於x,真正起做用仍是調用時主函數中輸入的參數值,因此你這樣寫也沒有問題。不過用變量cc_list好,閱讀起來不會引發混淆,無論你是下10國國旗仍是20國國旗。若是你download_many中是20國國旗做爲變量,調用時輸入10國國旗爲參數,看起來比較彆扭。
本身之後寫代碼要學習這種寫法!
https://www.zhihu.com/question/21123544
def case1(somearg): pass
def case2(somearg): pass
def case3(somearg): pass switch={ 1: case1, 2: case2, 3: case3 } switch[case](arg)
from enum import Enum EventType=Enum('EventType','tick bar signal') EventType.tick Out[29]: <EventType.tick: 1> dir(EventType) Out[30]: ['__class__', '__doc__', '__members__', '__module__', 'bar', 'signal', 'tick']
dic ={'a': 1, 'b': 2, 'c': 3} for n,buf in enumerate(dic): print(n,buf) # 0 a # 1 b # 2 c
結論:直接賦值比for循環要快
# 下面代碼爲 將一個對象全部屬性 給 另外一個對象,注意test1不行。
from datetime import datetime class A(): name = "runoob" def test(a, b): for k, v in a.__dict__.items(): setattr(b, k, v) def test1(a, b): for k, v in a.__dict__.items(): b.k = v def test2(a, b): b.a = a.a b.b = a.b b.c = a.c b.d = a.d b.e = a.e b.f = a.f def run(f, a, b): start = datetime.now() for i in range(10000): # 0000000 f(a, b) end = datetime.now() print(end - start) dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'aa': 1, 'ba': 2, 'ca': 3, 'da': 4, 'ea': 5, 'fa': 6} a = A() for k, v in dic.items(): setattr(a, k, v) print(a.__dict__) b = A() run(test, a, b) print(b.__dict__) # test # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} # 0:00:09.460686 # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} # test1 # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} # 0:00:05.086406 # {'k': 6} # test2 # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} # 0:00:03.672156 # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
# 下面代碼爲 將一個字典全部鍵值對 做爲 一個對象的屬性
print('ok') from datetime import datetime class A(): name = "runoob" def test(a, b): for k, v in a.items(): setattr(b, k, v) def test1(a,b): for k,v in a.items(): b.__setattr__(k,v) def test2(a, b): b.a = a['a'] b.b = a['b'] b.c = a['c'] b.d = a['d'] b.e = a['e'] b.f = a['f'] b.aa = a['aa'] b.ba = a['ba'] b.ca = a['ca'] b.da = a['da'] b.ea = a['ea'] b.fa = a['fa'] def run(f, a, b): start = datetime.now() for i in range(10000): # 0000000 f(a, b) end = datetime.now() print(end - start) a = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'aa': 1, 'ba': 2, 'ca': 3, 'da': 4, 'ea': 5, 'fa': 6} b = A() run(test1, a, b) print(b.__dict__) # 結果:賦值比for循環快