day4-python以內置函數和匿名函數

 

1、內置函數html

截止到python版本3.6.2,python爲咱們提供了68個內置函數。這些函數是python提供直接能夠拿來使用的全部函數。python

abs() dict() help() min() setattr()
all()  dir()  hex()  next()  slice() 
any()  divmod()  id()  object()  sorted() 
ascii() enumerate()  input()  oct()  staticmethod() 
bin()  eval()  int()  open()  str() 
bool()  exec()  isinstance()  ord()  sum() 
bytearray()  filter()  issubclass()  pow()  super() 
bytes() float()  iter()  print()  tuple() 
callable() format()  len()  property()  type() 
chr() frozenset()  list()  range()  vars() 
classmethod()  getattr() locals()  repr()  zip() 
compile()  globals() map()  reversed()  __import__() 
complex()  hasattr()  max()  round()  
delattr() hash()  memoryview()  set()  

把這些函數分紅6大類:面試

一、做用域相關算法

基於字典的形式獲取局部變量和全局變量shell

globals()——獲取全局變量的字典數組

locals()——獲取執行本方法所在命名空間內的局部變量的字典緩存

 1 a = 1
 2 b = 2
 3 print(locals())
 4 print(globals())
 5 # 這兩個同樣,由於是在全局執行的。
 6 
 7 ##########################
 8 
 9 def func(argv):
10     c = 2
11     print(locals())
12     print(globals())
13 func(3)
14 
15 #這兩個不同,locals() {'argv': 3, 'c': 2}
16 #globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__': None, '__file__': 'D:/lnh.python/.../內置函數.py', 'func': <function func at 0x0000024408CF90D0>, '__name__': '__main__', '__package__': None}
代碼示例

 二、其餘數據結構

1)字符串類型代碼的執行app

eval()  將字符串類型的代碼執行並返回結果ide

1 print(eval('1+2+3+4'))

exec()  將字符串類型的代碼執行

1 print(exec("1+2+3+4"))
2 exec("print('hello,world')")
 1 code = '''
 2 import os 
 3 print(os.path.abspath('.'))
 4 '''
 5 code = '''
 6 print(123)
 7 a = 20
 8 print(a)
 9 '''
10 a = 10
11 exec(code,{'print':print},)
12 print(a)
指定global參數

 compile  將字符串類型的代碼編譯。代碼對象可以經過exec語句來執行或者eval()進行求值。

參數說明:   

1. 參數source:字符串或者AST(Abstract Syntax Trees)對象。即須要動態執行的代碼段。  

2. 參數 filename:代碼文件名稱,若是不是從文件讀取代碼則傳遞一些可辨認的值。當傳入了source參數時,filename參數傳入空字符便可。  

3. 參數model:指定編譯代碼的種類,能夠指定爲 ‘exec’,’eval’,’single’。當source中包含流程語句時,model應指定爲‘exec’;當source中只包含一個簡單的求值表達式,model應指定爲‘eval’;當source中包含了交互式命令語句,model應指定爲'single'。

 1 >>> #流程語句使用exec
 2 >>> code1 = 'for i in range(0,10): print (i)'
 3 >>> compile1 = compile(code1,'','exec')
 4 >>> exec (compile1)
 5 3
 6 7
 7 
 8 
 9 >>> #簡單求值表達式用eval
10 >>> code2 = '1 + 2 + 3 + 4'
11 >>> compile2 = compile(code2,'','eval')
12 >>> eval(compile2)
13 
14 
15 >>> #交互語句用single
16 >>> code3 = 'name = input("please input your name:")'
17 >>> compile3 = compile(code3,'','single')
18 >>> name #執行前name變量不存在
19 Traceback (most recent call last):
20   File "<pyshell#29>", line 1, in <module>
21     name
22 NameError: name 'name' is not defined
23 >>> exec(compile3) #執行時顯示交互命令,提示輸入
24 please input your name:'pythoner'
25 >>> name #執行後name變量有值
26 "'pythoner'"

 2)輸入輸出相關

input()  輸入

1 s = input("請輸入內容 : ")  #輸入的內容賦值給s變量
2 print(s)  #輸入什麼打印什麼。數據類型是str
input的用法

print  輸出

1 def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
2     """
3     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
4     file:  默認是輸出到屏幕,若是設置爲文件句柄,輸出到文件
5     sep:   打印多個值之間的分隔符,默認爲空格
6     end:   每一次打印的結尾,默認爲換行符
7     flush: 當即把內容輸出到流文件,不做緩存
8     """
print源碼剖析
1 f = open('tmp_file','w')
2 print(123,456,sep=',',file = f,flush=True)
file關鍵字的說明
1 import time
2 for i in range(0,101,2):  
3      time.sleep(0.1)
4      char_num = i//2      #打印多少個'*'
5      per_str = '\r%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num)
6      print(per_str,end='', flush=True)
7 #注意  : \r 能夠把光標移動到行首但不換行
打印進度條

 3)內存相關

id(o) o是參數,返回一個變量的內存地址

hash(o) o是參數,返回一個可hash變量的哈希值,不可hash的變量被hash以後會報錯。

1 t = (1,2,3)
2 l = [1,2,3]
3 print(hash(t))  #可hash
4 print(hash(l))  #會報錯
5 
6 '''
7 結果:
8 TypeError: unhashable type: 'list'
9 '''
hash實例

hash函數會根據一個內部的算法對當前可hash變量進行處理,返回一個int數字。

*每一次執行程序,內容相同的變量hash值在這一次執行過程當中不會發生改變。

 4)文件操做相關

open()  打開一個文件,返回一個文件操做符(文件句柄)

操做文件的模式有r,w,a,r+,w+,a+ 共6種,每一種方式均可以用二進制的形式操做(rb,wb,ab,rb+,wb+,ab+)

能夠用encoding指定編碼。

 5)模塊相關

__import__導入一個模塊

1 # 方法1
2 import time
3 
4 # 方法2
5 os = __import__('os')
6 print(os.path.abspath('.'))
導入模塊

6)幫助

在控制檯執行help()進入幫助模式。能夠隨意輸入變量或者變量的類型。輸入q退出

或者直接執行help(o),o是參數,查看和變量o有關的操做。。。

7)調用相關

callable(o),o是參數,看這個變量是否是可調用。

若是o是一個函數名,就會返回True

1 def func():pass
2 print(callable(func))  #參數是函數名,可調用,返回True
3 print(callable(123))   #參數是數字,不可調用,返回False
callable實例

8)查看內置屬性

查看參數所屬類型的全部內置方法

dir() 默認查看全局空間內的屬性,也接受一個參數,查看這個參數內的方法或變量

1 print(dir(list))  #查看列表的內置方法
2 print(dir(int))  #查看整數的內置方法
查看某變量/數據類型的內置方法

 三、基礎數據類型相關

1)和數字相關

數字——數據類型相關:bool,int,float,complex

bool :用於將給定參數轉換爲布爾類型,若是沒有參數,返回 False。

int:函數用於將一個字符串或數字轉換爲整型。

1 print(int())  # 0
2 
3 print(int('12'))  # 12
4 
5 print(int(3.6))  # 3
6 
7 print(int('0100',base=2))  # 將2進制的 0100 轉化成十進制。結果爲 4
View Code

float:函數用於將整數和字符串轉換成浮點數。

complex:函數用於建立一個值爲 real + imag * j 的複數或者轉化一個字符串或數爲複數。若是第一個參數爲字符串,則不須要指定第二個參數。。

 1 >>>complex(1, 2)
 2 (1 + 2j)
 3  
 4 >>> complex(1)    # 數字
 5 (1 + 0j)
 6  
 7 >>> complex("1")  # 當作字符串處理
 8 (1 + 0j)
 9  
10 # 注意:這個地方在"+"號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",不然會報錯
11 >>> complex("1+2j")
12 (1 + 2j)
View Code

數字——進制轉換相關:bin,oct,hex

bin:將十進制轉換成二進制並返回。

oct:將十進制轉化成八進制字符串並返回。

hex:將十進制轉化成十六進制字符串並返回。

1 print(bin(10),type(bin(10)))  # 0b1010 <class 'str'>
2 print(oct(10),type(oct(10)))  # 0o12 <class 'str'>
3 print(hex(10),type(hex(10)))  # 0xa <class 'str'>
View Code

數字——數學運算:abs,divmod,min,max,sum,round,pow

abs:函數返回數字的絕對值。

divmod:計算除數與被除數的結果,返回一個包含商和餘數的元組(a // b, a % b)。

round:保留浮點數的小數位數,默認保留整數。

pow:求x**y次冪。(三個參數爲x**y的結果對z取餘)

 1 print(abs(-5))  # 5
 2 
 3 print(divmod(7,2))  # (3, 1)
 4 
 5 print(round(7/3,2))  # 2.33
 6 print(round(7/3))  # 2
 7 print(round(3.32567,3))  # 3.326
 8 
 9 print(pow(2,3))  # 兩個參數爲2**3次冪
10 print(pow(2,3,3))  # 三個參數爲2**3次冪,對3取餘。
View Code

sum:對可迭代對象進行求和計算(可設置初始值)。

min:返回可迭代對象的最小值(可加key,key爲函數名,經過函數的規則,返回最小值)。

max:返回可迭代對象的最大值(可加key,key爲函數名,經過函數的規則,返回最大值)。

 1 print(sum([1,2,3]))
 2 print(sum((1,2,3),100))
 3 
 4 print(min([1,2,3]))  # 返回此序列最小值
 5 
 6 ret = min([1,2,-5,],key=abs)  # 按照絕對值的大小,返回此序列最小值
 7 print(ret)
 8 
 9 dic = {'a':3,'b':2,'c':1}
10 print(min(dic,key=lambda x:dic[x]))
11 # x爲dic的key,lambda的返回值(即dic的值進行比較)返回最小的值對應的鍵
12 
13 
14 print(max([1,2,3]))  # 返回此序列最大值
15 
16 ret = max([1,2,-5,],key=abs)  # 按照絕對值的大小,返回此序列最大值
17 print(ret)
18 
19 dic = {'a':3,'b':2,'c':1}
20 print(max(dic,key=lambda x:dic[x]))
21 # x爲dic的key,lambda的返回值(即dic的值進行比較)返回最大的值對應的鍵
View Code

 2)和數據結構相關

 

序列——列表和元組相關的:list和tuple

list:將一個可迭代對象轉化成列表(若是是字典,默認將key做爲列表的元素)。

tuple:將一個可迭代對象轉化成元祖(若是是字典,默認將key做爲元祖的元素)。

 1 l = list((1,2,3))
 2 print(l)
 3 
 4 l = list({1,2,3})
 5 print(l)
 6 
 7 l = list({'k1':1,'k2':2})
 8 print(l)
 9 
10 tu = tuple((1,2,3))
11 print(tu)
12 
13 tu = tuple([1,2,3])
14 print(tu)
15 
16 tu = tuple({'k1':1,'k2':2})
17 print(tu)
View Code

序列——字符串相關的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

str:將數據轉化成字符串。

format:與具體數據相關,用於計算各類小數,精算等。

 1 #字符串能夠提供的參數,指定對齊方式,<是左對齊, >是右對齊,^是居中對齊
 2 print(format('test', '<20'))
 3 print(format('test', '>20'))
 4 print(format('test', '^20'))
 5 
 6 #整形數值能夠提供的參數有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
 7 >>> format(3,'b') #轉換成二進制
 8 '11'
 9 >>> format(97,'c') #轉換unicode成字符
10 'a'
11 >>> format(11,'d') #轉換成10進制
12 '11'
13 >>> format(11,'o') #轉換成8進制
14 '13'
15 >>> format(11,'x') #轉換成16進制 小寫字母表示
16 'b'
17 >>> format(11,'X') #轉換成16進制 大寫字母表示
18 'B'
19 >>> format(11,'n') #和d同樣
20 '11'
21 >>> format(11) #默認和d同樣
22 '11'
23 
24 #浮點數能夠提供的參數有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
25 >>> format(314159267,'e') #科學計數法,默認保留6位小數
26 '3.141593e+08'
27 >>> format(314159267,'0.2e') #科學計數法,指定保留2位小數
28 '3.14e+08'
29 >>> format(314159267,'0.2E') #科學計數法,指定保留2位小數,採用大寫E表示
30 '3.14E+08'
31 >>> format(314159267,'f') #小數點計數法,默認保留6位小數
32 '314159267.000000'
33 >>> format(3.14159267000,'f') #小數點計數法,默認保留6位小數
34 '3.141593'
35 >>> format(3.14159267000,'0.8f') #小數點計數法,指定保留8位小數
36 '3.14159267'
37 >>> format(3.14159267000,'0.10f') #小數點計數法,指定保留10位小數
38 '3.1415926700'
39 >>> format(3.14e+1000000,'F')  #小數點計數法,無窮大轉換成大小字母
40 'INF'
41 
42 #g的格式化比較特殊,假設p爲格式中指定的保留小數位數,先嚐試採用科學計數法格式化,獲得冪指數exp,若是-4<=exp<p,則採用小數計數法,並保留p-1-exp位小數,不然按小數計數法計數,並按p-1保留小數位數
43 >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留0位小數點
44 '3e-05'
45 >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留1位小數點
46 '3.1e-05'
47 >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留2位小數點
48 '3.14e-05'
49 >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留0位小數點,E使用大寫
50 '3.14E-05'
51 >>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留0位小數點
52 '3'
53 >>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留1位小數點
54 '3.1'
55 >>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留2位小數點
56 '3.14'
57 >>> format(0.00003141566,'.1n') #和g相同
58 '3e-05'
59 >>> format(0.00003141566,'.3n') #和g相同
60 '3.14e-05'
61 >>> format(0.00003141566) #和g相同
62 '3.141566e-05'
View Code

bytes:用於不一樣編碼之間的轉化。

 1 # s = '你好'
 2 # bs = s.encode('utf-8')
 3 # print(bs)
 4 # s1 = bs.decode('utf-8')
 5 # print(s1)
 6 # bs = bytes(s,encoding='utf-8')
 7 # print(bs)
 8 # b = '你好'.encode('gbk')
 9 # b1 = b.decode('gbk')
10 # print(b1.encode('utf-8'))
View Code

bytearry:返回一個新字節數組。這個數組裏的元素是可變的,而且每一個元素的值範圍: 0 <= x < 256。

memoryview

1 ret = bytearray('alex',encoding='utf-8')
2 print(id(ret))
3 print(ret[0])
4 ret[0] = 65
5 print(ret)
6 print(id(ret))
bytearray
1 ret = memoryview(bytes('你好',encoding='utf-8'))
2 print(len(ret))
3 print(bytes(ret[:3]).decode('utf-8'))
4 print(bytes(ret[3:]).decode('utf-8'))
memoryview

ord:輸入字符找該字符編碼的位置

chr:輸入位置數字找出其對應的字符

ascii:是ascii碼中的返回該值,不是就返回/u...

 1 # ord 輸入字符找該字符編碼的位置
 2 # print(ord('a'))
 3 # print(ord('中'))
 4 
 5 # chr 輸入位置數字找出其對應的字符
 6 # print(chr(97))
 7 # print(chr(20013))
 8 
 9 # 是ascii碼中的返回該值,不是就返回/u...
10 # print(ascii('a'))
11 # print(ascii('中'))
View Code

repr:返回一個對象的string形式(原形畢露)。

1 # %r  原封不動的寫出來
2 # name = 'taibai'
3 # print('我叫%r'%name)
4 
5 # repr 原形畢露
6 print(repr('{"name":"alex"}'))
7 print('{"name":"alex"}')
View Code

序列:reversed,slice

reversed:將一個序列翻轉,並返回此翻轉序列的迭代器。

slice:構造一個切片對象,用於列表的切片。

1 l = (1,2,23,213,5612,342,43)
2 print(l)
3 print(list(reversed(l)))
reversed
1 l = (1,2,23,213,5612,342,43)
2 sli = slice(1,5,2)
3 print(l[sli])
slice

數據集合——字典和集合:dict,set,frozenset

dict:建立一個字典。

set:建立一個集合。

frozenset:返回一個凍結的集合,凍結後集合不能再添加或刪除任何元素。

數據集合:len,sorted,enumerate,all,any,zip,filter,map

len:返回一個對象中元素的個數。

sorted:對全部可迭代的對象進行排序操做。

 1 L = [('a', 1), ('c', 3), ('d', 4),('b', 2), ]
 2 sorted(L, key=lambda x:x[1])               # 利用key
 3 [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 4  
 5  
 6 students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
 7 sorted(students, key=lambda s: s[2])            # 按年齡排序
 8 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 9  
10 sorted(students, key=lambda s: s[2], reverse=True)    # 按降序
11 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
View Code

enumerate:枚舉,返回一個枚舉對象。

1 print(enumerate([1,2,3]))
2 for i in enumerate([1,2,3]):
3     print(i)
4 for i in enumerate([1,2,3],100):
5     print(i)
View Code

all:可迭代對象中,全都是True纔是True

any:可迭代對象中,有一個True 就是True

1 # all  可迭代對象中,全都是True纔是True
2 # any  可迭代對象中,有一個True 就是True
3 # print(all([1,2,True,0]))
4 # print(any([1,'',0]))
View Code

zip:函數用於將可迭代的對象做爲參數,將對象中對應的元素打包成一個個元組,而後返回由這些元組組成的列表。若是各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同。

1 l1 = [1,2,3,]
2 l2 = ['a','b','c',5]
3 l3 = ('*','**',(1,2,3))
4 for i in zip(l1,l2,l3):
5     print(i)
View Code

filter:過濾·。

1 #filter 過濾 經過你的函數,過濾一個可迭代對象,返回的是True
2 #相似於[i for i in range(10) if i > 3]
3 # def func(x):return x%2 == 0
4 # ret = filter(func,[1,2,3,4,5,6,7])
5 # print(ret)
6 # for i in ret:
7 #     print(i)
View Code

map:會根據提供的函數對指定序列作映射。

 1 >>>def square(x) :            # 計算平方數
 2 ...     return x ** 2
 3 ... 
 4 >>> map(square, [1,2,3,4,5])   # 計算列表各個元素的平方
 5 [1, 4, 9, 16, 25]
 6 >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函數
 7 [1, 4, 9, 16, 25]
 8  
 9 # 提供了兩個列表,對相同位置的列表數據進行相加
10 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
11 [3, 7, 11, 15, 19]
View Code

 四、迭代器/生成器相關

range:函數可建立一個整數對象,通常用在 for 循環中。

next:內部實際使用了__next__方法,返回迭代器的下一個項目。

 1 # 首先得到Iterator對象:
 2 it = iter([1, 2, 3, 4, 5])
 3 # 循環:
 4 while True:
 5     try:
 6         # 得到下一個值:
 7         x = next(it)
 8         print(x)
 9     except StopIteration:
10         # 遇到StopIteration就退出循環
11         break
View Code

 iter:函數用來生成迭代器。

1 from collections import Iterable
2 from collections import Iterator
3 l = [1,2,3]
4 print(isinstance(l,Iterable))  # True
5 print(isinstance(l,Iterator))  # False
6 
7 l1 = iter(l)
8 print(isinstance(l1,Iterable))  # True
9 print(isinstance(l1,Iterator))  # True
View Code

 五、反射相關

 

六、面向對象相關

type(o) 返回變量o的數據類型

# 標紅的必會
# 標黃的 是可以節省你的代碼
# 重點:min max sorted filter map

 2、匿名函數

 匿名函數:爲了解決那些功能很簡單的需求而設計的一句話函數

1 #這段代碼
2 def calc(n):
3     return n**n
4 print(calc(10))
5  
6 #換成匿名函數
7 calc = lambda n:n**n
8 print(calc(10))

 

關於匿名函數格式的說明:

1 函數名 = lambda 參數 :返回值
2 
3 # 參數能夠有多個,用逗號隔開
4 # 匿名函數無論邏輯多複雜,只能寫一行,且邏輯執行結束後的內容就是返回值
5 # 返回值和正常的函數同樣能夠是任意數據類型

匿名函數並非真的不能有名字。

匿名函數的調用和正常的調用沒有什麼區別。

函數名(參數)

例1:練一練

1 # 函數
2 def add(a,b):
3     return a+b
4 
5 # 換成匿名函數
6 add = lambda a,b:a+b
7 print(add(1,2))

 例2:

 1 # 列表推導式
 2 [i**2 for i in range(10)]
 3 
 4 # 函數
 5 def func(num):
 6     return num ** 2
 7 for i in map(func,range(10)):print(i)
 8 
 9 # 匿名函數
10 for i in map(lambda num:num ** 2 ,range(10)):print(i)

 例3:

1 # 函數
2 def func(num):
3     return num%2
4 print(min(-2,3,-4,key=func))
5 
6 # 匿名行數
7 print(min(-2,3,-4,key=lambda num:num % 2))

 例4:

1 l=[3,2,100,999,213,1111,31121,333]
2 print(max(l))
3 
4 dic={'k1':10,'k2':100,'k3':30}
5 
6 
7 print(max(dic))
8 print(dic[max(dic,key=lambda k:dic[k])])

 例5:

 1 res = map(lambda x:x**2,[1,5,7,4,8])
 2 for i in res:
 3     print(i)
 4 
 5 # 輸出:
 6 '''
 7 1
 8 25
 9 49
10 16
11 64
12 '''

 例6:

1 res = filter(lambda x:x>10,[5,8,11,9,15])
2 for i in res:
3     print(i)
4 
5 # 輸出:
6 '''
7 11
8 15
9 '''

 面試題:

 1 # 1.下面程序的輸出結果是:
 2 d = lambda p:p*2
 3 t = lambda p:p*3
 4 x = 2
 5 x = d(x)
 6 x = t(x)
 7 x = d(x)
 8 print(x)
 9 
10 # 2.現有兩元組(('a'),('b')),(('c'),('d')),請使用python中匿名函數生成列表[{'a':'c'},{'b':'d'}]
11 def func(t):
12     return {t[0]:t[1]}
13 ret = map(func,zip((('a'),('b')),(('c'),('d'))))
14 print(list(ret))
15 
16 ret = map(lambda t:{t[0]:t[1]},zip((('a'),('b')),(('c'),('d'))))
17 print(list(ret))
18 
19 #答案一
20 test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
21 print(test(t1,t2))
22 #答案二
23 print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))
24 #還能夠這樣寫
25 print([{i:j} for i,j in zip(t1,t2)])
26 
27 # 3.如下代碼的輸出是什麼?請給出答案並解釋。
28 def multipliers():
29     return [lambda x:i*x for i in range(4)]
30 print([m(2) for m in multipliers()])
31 # 請修改multipliers的定義來產生指望的結果。
32 def multipliers():
33     lst = []
34     for i in range(4):
35         lst.append(lambda x:i*x)
36     return lst
37 print([m(2) for m in multipliers()])
38 
39 def multipliers():
40     return [lambda x:i*x for i in range(4)]
41 print([m(2) for m in multipliers()])
42 
43 g = (lambda x:i*x for i in range(4))
44 print([m(2) for m in g])

 3、本章小結

其餘:input,print,type,hash,open,import,dir

str類型代碼執行:eval,exec

數字:bool,int,float,abs,divmod,min,max,sum,round,pow

序列——列表和元組相關的:list和tuple

序列——字符串相關的:str,bytes,repr

序列:reversed,slice

數據集合——字典和集合:dict,set,frozenset

數據集合:len,sorted,enumerate,zip,filter,map

1 # map filter sorted max min zip
2 def func(n):
3     if n%2 == 0:
4         return True
5 ret = filter(func,range(20))
6 ret = filter(lambda n: True if n%2 == 0 else False ,range(20))
7 ret = filter(lambda n: n%2 == 0 ,range(20))

 參考文檔:

https://docs.python.org/3/library/functions.html#object

相關文章
相關標籤/搜索