1、內置函數
官方文檔:點擊 html
![](http://static.javashuo.com/static/loading.gif)
# 匿名函數 f=lambda a,b:a+b print(f(2,3)) # 5 # abs() 取絕對值 print(abs(-111)) # 111 # all() 循環可迭代對象的每一個元素,都爲真則返回True,不然返回假 # 0,None ,"",[],(),{} 是假的 print(all([11,22])) # True # any 有一個爲真,所有都爲真 print(any([0,0,None])) #False # ascii 在對象類中找 __repr__,獲取返回值 class D(): def __repr__(self): return 'hello' d=D() print(ascii(d)) #hello # bin 將十進制轉換成2進制 # oct() hex() print(bin(11)) #0b1011 #各類進制轉換成十進制能夠用int() print(int('11',base=2)) #將二進制'11'轉換成十進制數 3 # bytearry 字節列表 # chr() 找到數字對於的ascii碼 # ord() ascii碼對應的數字 # chr ord 只適用於ascii碼 print(chr(65)) # A print(ord('A')) # 65 # callable 後面加個括號是看否能執行 #complie() 接受一個字符串,將其轉換成函數代碼 # divmod 返回除法的(值,餘數) print(divmod(10,3)) #(3,1) # eval 計算器的功能 返回結果 print(eval('a+60',{'a':90})) # 150 print(eval('3+4*6/7+((1+2)-5)')) # 4.428571428571429 #exec,執行python代碼,沒有返回值 exec("for i in range(5):print(i)") # 直接循環輸出0,1,2,3,4 # filter(函數,可迭代的對象) # 循環能夠迭代的對象,傳入函數中執行,若是不符合就過濾 def fun(s): #定義判斷一個數是不是偶數的函數 if s%2==0: return True else: return False ret=filter(fun,[1,2,3,4,5,6,7,8]) for i in ret: print(i) # 打印出2,4,6,8 #用匿名函數改寫一下 ret1=filter(lambda x:x%2==0,[1,2,3,4,5,6,7,8]) for i in ret1: print(i) # 2,4,6,8 #map將傳入的函數依次做用到序列的每一個元素,並把結果做爲新的Iterator返回 ret=map(lambda x:x+100,[1,2,3]) for i in ret: print(i) # 101,102,103 # globals() 獲取當前文件的全部全局變量 # locals() 獲取當前文件的全部局部變量 # hash() 獲取哈希值 # isinstance 看某個對象是否是某個類建立的 #iter() 建立一個能夠被迭代的對象 next()取下一個值 k=iter([1,2,3,4]) print(next(k)) # 1 # pow() 求指數 print(pow(2,10)) #1024 # round() 四捨五入 # #zip l1=[1,2,3,4] l2=['a','b','c','d'] k=zip(l1,l2) for i in k: print(i) #打印出(1,a),(2,b)....
![](http://static.javashuo.com/static/loading.gif)
""" 匿名函數: 與有名函數有相同的做用域,可是匿名意味着引用計數爲0,使用一次就釋放,除非讓其有名字,可是讓其有名字就沒有意義 有名函數:循環使用,保存了名字,經過名字就能夠重複引用函數功能 匿名函數:一次性使用,隨時隨時定義 應用:max,min,sorted,map,reduce,filter """ def func(x,y,z=1): return x+y+z lambda x,y,z=1:x+y+z func=lambda x,y,z=1:x+y+z #讓其有名字就沒有意義 func(1,2,3)
![](http://static.javashuo.com/static/loading.gif)
""" 三元表達式: 格式: res=值1 if 條件 else 值2 """ name = "tom" res = "是 tom" if name == "tom" else "不是tom" print(res) #是 tom
![](http://static.javashuo.com/static/loading.gif)
""" 列表推導式: 優勢:方便,改變了編程習慣,可稱之爲聲明式編程 """ lis_gen = [ i for i in range(1,10)] #列表推導式 經過計算生成一個列表 print(lis_gen) #[1, 2, 3, 4, 5, 6, 7, 8, 9] lis1_gen = [i for i in range(1,10) if i%2 == 0] #生成一個偶數的列表 print(lis1_gen) #[2, 4, 6, 8] lis2_gen = [ i * i for i in range(1,10) if i%2 == 1] #生成以個奇數乘自已自己奇數的列表 print(lis2_gen) #[1, 9, 25, 49, 81]
![](http://static.javashuo.com/static/loading.gif)
#推導式的套路 """ variable = [out_exp_res for out_exp in input_list if out_exp == 2] out_exp_res: 列表生成元素表達式,能夠是有返回值的函數。 for out_exp in input_list: 迭代input_list將out_exp傳入out_exp_res表達式中。 if out_exp == 2: 根據條件過濾哪些值能夠。 """ #列表推導式 #例一:30之內全部能被3整除的數 multiples = [i for i in range(30) if i % 3 is 0] print(multiples) # [0, 3, 6, 9, 12, 15, 18, 21, 24, 27] #例二:30之內全部能被3整除的數的平方 def squared(x): return x*x multiples = [squared(i) for i in range(30) if i % 3 is 0] print(multiples) #[0, 9, 36, 81, 144, 225, 324, 441, 576, 729] #字典推導式 mcase = {'a': 10, 'b': 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency,type(mcase_frequency)) #{34: 'b', 10: 'a'} <class 'dict'> #集合推導式 squared = {x**2 for x in [1, -1, 2]} print(squared) #{1, 4} #求(x,y)其中x是0-5之間的偶數,y是0-5之間的奇數組成的元祖列表 print([(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]) #[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)] #求M中3,6,9組成的列表M = [[1,2,3],[4,5,6],[7,8,9]] M = [[1,2,3],[4,5,6],[7,8,9]] print([row[2] for row in M]) #[3, 6, 9] ########################################## def func():pass print(callable(func)) # True 判斷一個變量是否能夠調用 函數能夠被調用 print(dir(123)) #返回值是列表 # 查看數字類型中含有哪些方法 print(eval('1+2-3*4/5')) # 0.6000000000000001 執行字符串數據類型的代碼而且將值返回 exec('print(123)') #123 執行字符串數據類型的代碼但沒有返回值 ################## """ zip函數接收一個或多個可迭代對象做爲參數,最後返回一個迭代器: zip(x, y) 會生成一個可返回元組 (m, n) 的迭代器,其中m來自x,n來自y。 一旦其中某個序列迭代結束,迭代就宣告結束。 所以迭代長度跟參數中最短的那個序列長度一致。 """ x = [1, 3, 5, 7, 9] y = [2, 4, 6, 8] for m, n in zip(x, y): print(m,n) """ 1 2 3 4 5 6 7 8 """ #若是上面不是你想要的效果,那麼你還能夠使用 itertools.zip_longest() 函數來代替這個例子中的zip。 from itertools import zip_longest x = [1, 3, 5, 7, 9] y = [2, 4, 6, 8] for m, n in zip_longest(x, y): print(m,n) """ 1 2 3 4 5 6 7 8 9 None """ keys = ["name", "age", "salary"] values = ["Andy", 18, 50] print(dict(zip(keys, values))) #{'name': 'Andy', 'salary': 50, 'age': 18} print(list(zip(keys, values))) #[('name', 'Andy'), ('age', 18), ('salary', 50)] print(tuple(zip(keys, values))) #(('name', 'Andy'), ('age', 18), ('salary', 50)) print(set(zip(keys, values))) #{('age', 18), ('salary', 50), ('name', 'Andy')}
![](http://static.javashuo.com/static/loading.gif)
""" eval與exec 語法: eval(str,[,globasl[,locals]]) exec(str,[,globasl[,locals]]) """ #示例1: s='1+2+3' print(eval(s)) #eval用來執行表達式,並返回表達式執行的結果 返回6 print(exec(s)) #exec用來執行語句,不會返回任何值,也就是返回None #示例2: dic = "{'x':3}" print(eval(dic),type(eval(dic))) #{'x': 3} <class 'dict'> print(exec(dic),type(exec(dic))) #返回None <class 'NoneType'> # print(eval('for i in range(10):print(i)')) #語法錯誤,eval不能執行表達式 print(exec('for i in range(3):print(i)')) """ 0 1 2 None """
![](http://static.javashuo.com/static/loading.gif)
salaries = { 'tom': 3000, 'jack': 122121221, 'rose': 100, } k_and_v = zip(salaries.values(), salaries.keys()) print(k_and_v) # <zip object at 0x0000000000C07BC8> print(max(k_and_v)) # (122121221, 'jack') #k_and_v是迭代器,於是只能訪問一次 # print(min(k_and_v)) #報錯了 k_and_v2 = zip(salaries.values(), salaries.keys()) # print(list(k_and_v2)) # [(3000, 'tom'), (122121221, 'jack'), (100, 'rose')] # print(list(zip(k_and_v2))) #[((3000, 'tom'),), ((122121221, 'jack'),), ((100, 'rose'),)] # print(list(zip(*k_and_v2))) #[(3000, 122121221, 100), ('tom', 'jack', 'rose')] print(list(map(list, zip(*k_and_v2)))) #[[3000, 122121221, 100], ['tom', 'jack', 'rose']]
max/min
- max函數處理的是可迭代對象,至關於一個for循環取出每個元素進行比較
- 注意:不一樣類型之間不能進行比較
- 每個元素間進行比較,是從每個元素的第一個位置依次比較,若是這一個位置分出大小,後面的都不須要比較了,直接得出這兩元素的大小
![](http://static.javashuo.com/static/loading.gif)
""" max min 字典的運算:最小值,最大值,排序 迭代字典,取得是key,於是比較的是key的最大和最小值 """ salaries={ 'tom':3000, 'jack':122121221, 'rose':100, } #比較的是key print(max(salaries)) #tom print(min(salaries)) #jack #比較的是values print(max(salaries.values())) #122121221 print(min(salaries.values())) #100 #即要key也要value print(max(zip(salaries.values(),salaries.keys()))) #(122121221, 'jack') print(max(salaries)) #jack people=[ {'name':'tom','age':12}, {'name':'rose','age':50}, {'name':'jack','age':99}, ] print('===',max(people,key=lambda dic:dic['age'])) #=== {'age': 99, 'name': 'jack'}
2、高階函數
函數做爲參數傳入或者return返回一個函數,知足其中一個條件,這樣的函數就稱爲高階函數。python
一、map函數(映射)
map函數接受兩個參數,一個是函數,一個可迭代的對象(iterable),map將傳入的函數依次做用到序列的每一個元素,並把結果做爲新的 可迭代的對象 的結果返回編程
![](http://static.javashuo.com/static/loading.gif)
number = [1,2,3,4,5,6] #1.用普通函數定義方法 def add_one(x): return x+1 def map_test(func,arrey): res = [] for i in arrey: i = func(i) res.append(i) return res print(map_test(add_one,number)) #[2, 3, 4, 5, 6, 7] #2.用lambda函數定義的獲得結果,藉助1定義的map_test函數 print(map_test(lambda x:x+1,number)) #[2, 3, 4, 5, 6, 7] #3.用map()自己函數去定義 print(map(lambda x:x+1 ,number)) #<map object at 0x00000000010EAC18> 返回一個可迭代對象 print(list(map(lambda x:x+1 ,number))) #[2, 3, 4, 5, 6, 7] #注:map()得出的結果是一個iterator ,須要用list()函數讓它個整個序列都計算出來返回一個list
二、filter函數(過濾)
filter()函數用於過濾序列和map()相似,filter()也接受一個函數和一個可迭代的對象(iterable),不一樣的是fillter()把傳入的函數依次做用於每一個元素,而後根據返回值是True仍是False決定保留仍是丟棄該元素。數組
![](http://static.javashuo.com/static/loading.gif)
# 把列表中空字符串,空元素,都去掉 aa = ['A', '', 'B', None, 'C', ' '] #1.自定義函數測試 def not_empty(s): return s and s.strip() def filter_test(func,iter): res = [] for i in iter: i = func(i) if i: res.append(i) return res print(filter_test(not_empty,aa)) #['A', 'B', 'C'] #2.用lambda函數定義的獲得結果 print(filter_test(lambda s:s and s.strip(),aa)) #['A', 'B', 'C'] #3.filter內置函數測試 print(filter(not_empty,aa))#<filter object at 0x00000000010FAC18> print(list(filter(not_empty,aa)))#['A', 'B', 'C'] #注:filter()函數返回的是一個iterator,內存地址,須要看內存地址的值, 用list()函數或得該地址的值
三、reduce函數
reduce(function, sequence, initial=None) 在python2能夠直接用reduce()函數,在python3須要導入reduce模塊 from functools import reduce reduce函數,將function做用sequence序列的元素,每次攜帶一對(先前的結果以及下一序列的元素),獲得一個最終結果的返回值app
![](http://static.javashuo.com/static/loading.gif)
from functools import reduce #使用reduce(),結合lambda() number1 = [2, 3, 4, 10] print(reduce(lambda x, y: x * y, number1)) # 240 # 1.普通函數定義 def mul(x, y): return x * y # 返回獲得兩個數相乘的結果 def reduce_test(func, seq, init=None): if init is None: res = seq.pop(0) # seq刪除第一個元素,並獲取刪除這個元素 賦值給res else: res = init for i in seq: res = func(res, i) # 循環一次,執行func這個函數 return res print(number1) #[2, 3, 4, 10] print(reduce_test(mul, number1)) # 240 print(number1) #[3, 4, 10] print(reduce_test(mul, number1, 10)) # 2400 print(number1) #[3, 4, 10] # 2.lambda函數,藉助reduce_test()函數定義 print(reduce_test(lambda x, y: x * y, number1, init=3)) # 720 print(number1) #[3, 4, 10]
四、sorted函數
sorted()函數也是一個高階函數,它還能夠接收一個key函數來實現自定義的排序,key指定的函數將做用於list的每個元素上,並根據key函數返回的結果進行排序。ide
![](http://static.javashuo.com/static/loading.gif)
# _*_coding:utf-8_*_ #sorted print(sorted([36, 5, -12, 9, -21], key=abs)) #[5, 9, -12, -21, 36] print(sorted([36, 5, -12, 9, -21], key=abs, reverse=True)) #reverse=True 倒序 #[36, -21, -12, 9, 5] #成績從高到底排序 li = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] print(sorted(li, key=lambda x: x[1], reverse=True)) #[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)] #以列表中每一個元素的第二個字母倒序排序 li = ['alex', 'egon', 'smith', 'pizza', 'alen'] print(sorted(li, key=lambda x: x[1], reverse=True)) #map name=['alex','wupeiqi','yuanhao','egon'] def nb(x): return x+'_nb' res = map(nb,name) print(list(res)) #['alex_nb', 'wupeiqi_nb', 'yuanhao_nb', 'nezha_nb'] #用filter函數處理數字列表,將列表中全部的偶數篩選出來 num = [1,3,5,6,7,8] def func(x): if x%2 == 0: return True ret = filter(func,num) print(list(ret)) #[6, 8] #用filter過濾出,單價大於100的股票有哪些 portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] f = filter(lambda d:d['price']>=100,portfolio) print(list(f))