Python全栈之路系列----之-----内置函数和匿名函数lamdba
引子
什么是內置函數(shù)?
內置函數(shù)就是python 提供給我們直接拿來就可以用的函數(shù)
? 內置函數(shù)--內置命名空間
? 只管調用 不管實現(xiàn)
總共68個
def func(): == #這是自己定義的函數(shù)
pass
print() == #這是python 提供的內置函數(shù)
?
內置函數(shù)分為六大類,總數(shù)68個:
1.作用域相關的有兩個
2.迭代器生成器相關的有三個
3.基礎數(shù)據(jù)類型相關的有三十八個
4..面向對象相關的有九個
5.反射相關的有四個
6.其他的有十二個
?
標紅色的為必會方法...不....會....混...不....下..去...
第一類:作用域相關函數(shù)兩個
局部作用域中的變量 —— locals()? #本地
全局作用域中的變量 —— globals()
在全局執(zhí)行這兩個方法,結果相同
在局部執(zhí)行,locals表示函數(shù)內的名字,globals始終不變
?
第二類迭代器生成器相關函數(shù)的有三個
iter?? ,?? next?? ,?? range
所有可以調用雙下方法的都可以寫成加?? ()?? 執(zhí)行
next()????? 會在生成器中常用到
range()??? 會常用到? 范圍和步長
iter()??????? 不常用 ,只要是可迭代的都會有iter方法
在python里 要盡量少去調用雙下方法# def iter(iterable): # return iterable.__iter__()#print([1,2,3].__iter__()) #內置的特殊成員 # iterator = iter({1,2,3,4}) # # def next(iterator): # # return iterator.__next__() # print(next(iterator)) #iterator.__next__() # print(next(iterator)) # print(next(iterator))range(100) #[0,99] [0,100) range(10,100) #[10,99] range(10,100,2) #[10,99]隔一個取一個 #可迭代對象 最好循環(huán)取結果?
第三類其他類十二個
小類1>>字符串類型代碼執(zhí)行
eval??? exec?? compile
compile不要隨便用? 最好不用? 危險系數(shù)五顆星*****
#直接拿來執(zhí)行的方式一定不要隨便用
#如果非用不可,你也要做最起碼的檢測
?
eval : 有返回值
exec :沒有返回值
complie:當需要對某一個字符串數(shù)據(jù)類型的python代碼多次執(zhí)行的時候,就是用compile先編譯一下
# code1 = 'for i in range(0,10): print (i)' # compile1 = compile(code1,'','exec') #編譯 # # print(compile1) #code # exec(compile1)# code2 = '1 + 2 + 3 + 4' # compile2 = compile(code2,'','eval') # print(eval(compile2))# name = 'egon' # code3 = 'name = input("please input your name:")' # compile3 = compile(code3,'','single') # exec(compile3) # print(name)?
小類2>>輸入輸出
inpurt?? 和? print
input輸入時最好加上一些標識符? 更好理解的去輸入
print 重點有幾個方法?sep='***'? end=' ' file=f
結合代碼去理解
#a = input('>>>') # print(11232) # print(11232,1234,sep='***') # print('ajkdshkljaf',end=' ') # print('sagjkg') # print(12,34,56,sep=',') # print('%d,%d,%d'%(12,34,56)) # f = open('print_test','a',encoding='utf-8') # print(12146798,file=f)*************************************************
import time
for i in range(0,101,2):
??? time.sleep(0.1)
??? char_num = i//2????? #打印多少個'*'
??? per_str = '\r%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num)
??? print(per_str,end='', flush=True)
\r 可以把光標移動到行首但不換行
**************************************************
import sys
# for i in range(10):
#???? time.sleep(0.1)
#???? print(i*'*',end='')
#???? # sys.stdout.flush()
?
小類3內存相關>>hash和id
hash
?
hash的結果是拿到一個不變的數(shù)字和數(shù)據(jù)庫相關
但是重復哈希的值會變? 這和算法有關
可變的數(shù)據(jù)類型都不可以被哈希?? --列表 字典 集合
**************************************************
id???? 標志著一個數(shù)據(jù)的內存地址
is is not 不僅比較值的大小還比較內存地址是否一致
身份運算 ==只比較值的大小
?
?
# hashlib模塊 # print(hash('sdfsdf')) # print(hash('sdfsdf')) # print(hash('sdfsdf')) # print(hash('sdfsdf')) # 是一種摘要算法 每次hash的結果都不一樣 # print(hash((1,2,3,4,5,6,7))) # print(hash([12,2,54]))#可變的數(shù)據(jù)類型都不可以被哈希 列表 字典 集合 #hash的結果是一個數(shù)字 # hash作用 作為字典的key # 數(shù)據(jù)庫 字典# hash在python的一次執(zhí)行中,對于相同的可hash對象來說 # # # id()標志著一個數(shù)據(jù)的內存地址 # is is not 不僅比較值的大小還比較內存地址是否一致 # 身份運算 ==只比較值的大小?
?
?
小類4>>文件操作相關 open()
小類5>>模塊相關__import__但是要這樣用 import
小類6>>幫助 help() 退出 是q
小類7>>調用相關 判斷是否可調用 callable
小類8>>查看內置屬性? dir()看到數(shù)據(jù)類型里面有什么方法/內置屬性
print(dir(__builtins__)) 查看所有的
?
?
第四類基礎數(shù)據(jù)類型相關的有三十八個
基礎數(shù)據(jù)類型分為兩大類? : 數(shù)字相關里有三小類 和 數(shù)據(jù)結構相關 里有三小類
......????????????????????? .. ????????????????????????? .......
數(shù)字相關分為 1.數(shù)據(jù)類型 2.進制轉換 3.數(shù)學運算
數(shù)據(jù)結構相關分為 4. 序列? 5.數(shù)據(jù)集合? 6.相關內置函數(shù)
?
1.數(shù)據(jù)類型 包括 布爾bool , int , float ,complex
bool() :bool() 函數(shù)用于將給定參數(shù)轉換為布爾類型,如果沒有參數(shù),返回 False 返回值 返回 Ture 或 False。
int () :int() 函數(shù)用于將一個字符串會數(shù)字轉換為整型,去浮點數(shù),也就是轉換成數(shù)字
print(type(int('123')))?? print(type('123'))用于強轉數(shù)據(jù)類型
float() :float()函數(shù)用于將整數(shù)和字符串轉換成浮點數(shù)。 就是加上了末尾的小數(shù)點
compile():compile() 函數(shù)將一個字符串編譯為字節(jié)代碼。
2. 進制轉換 包括 bin oct hex
bin:轉換為二進制? oct 轉換成八進制? hex? 轉化成十六進制
3.數(shù)學運算 包括 abs? divmod? round pow ? sum min max ?? (都是重點)
abs:計數(shù)絕對值?? 相當于負數(shù)都是正數(shù)然后去計算
divmod:返回商取余 ,用于分頁
# ret = divmod(21, 5) # print(ret) # #商4余1 用于分頁 # #105 分10頁 余 5 11頁 # ret = divmod(105, 10) # print(ret) divmod?
round: 冪運算 print(pow(2,3))?
sum: 求和?? print(sum([1,2,3,4,5],'本錢'))?? print(sum(range(100)))
min: 計算最小值? max:計算最大值
可以接收散列的值,和可迭代的對象 key是一個函數(shù)名,判斷的結果根據(jù)函數(shù)的返回值來確定????
defult 如果可迭代對象為空,設置默認最小值
print(min(range(20))) print(min([1,2,3,4,5])) print(max([1,2,3,4,5])) print(min([-1,-5,6],key=abs))裝成絕對值 計算 print(max([1,-8,6],key=abs))裝成絕對值 計算 key根據(jù)函數(shù)的返回值 來判斷大小 min max 可以接收散列的名 和可迭代對象 key 是一個函數(shù)名 根據(jù)函數(shù)的返回值 來判斷大小 最大小值
4.序列:包括列表和原組 list? tuple? ? 主要用于強轉 reversed? 反轉?? slice 相當于切片
list() 方法用于將元組轉換為列表。tuple() 函數(shù)將列表轉換為元組。
注:元組與列表是非常類似的,區(qū)別在于元組的元素值不能修改,元組是放在括號中,列表是放于方括號中。
tuple({1:2,3:4}) #針對字典 會返回字典的key組成的tuple (1, 3) aList = [123, 'xyz', 'zara', 'abc']; aTuple = tuple(aList) Tuple elements : (123, 'xyz', 'zara', 'abc')aTuple = (123, 'xyz', 'zara', 'abc'); aList = list(aTuple) 列表元素 : [123, 'xyz', 'zara', 'abc'] 列表 元組reversed() 反轉數(shù)據(jù)? 就是倒著輸出
ret = reversed([1,2,3,4]) print (list(ret)) print (set(ret)) ret = reversed(range(0,20)) # print(list(ret)) # print(tuple(ret)) ret = reversed('ajagjfd') # print(ret)print('323'.join(list(ret))) reversed()?
4.1字符串類型 包括: str? format? bytes? bytearray memoryview? ord? chr? ascii? repr
str:強轉字符串
format:格式化輸出
?
>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序 'hello world'>>> "{0} {1}".format("hello", "world") # 設置指定位置 'hello world'>>> "{1} {0} {1}".format("hello", "world") # 設置指定位置 'world hello world'....................................................#!/usr/bin/python # -*- coding: UTF-8 -*-print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))# 通過字典設置參數(shù) site = {"name": "菜鳥教程", "url": "www.runoob.com"} print("網站名:{name}, 地址 {url}".format(**site))# 通過列表索引設置參數(shù) my_list = ['菜鳥教程', 'www.runoob.com'] print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是可選的 format#字符串可以提供的參數(shù),指定對齊方式,<是左對齊, >是右對齊,^是居中對齊 print(format('test', '<20')) print(format('test', '>20')) print(format('test', '^20')) format?
bytes:轉換成為bytes直接編碼? 解碼需要decode
# s = 'alex' # by = bytes(s,encoding='utf-8') #新華字典第n頁第m行第k個 # print(by) # print(by.decode('utf-8')) bytesbytearray:修改字符編碼組? 但是修改完不改變內存地址? 但是需要記住編碼號
#array == 數(shù)組 #alex [a,l,e,x] # s = 'alex' # ret = bytearray(s,encoding='utf-8') # print(id(ret)) # ret[0] = 65 # print(ret,id(ret)) # s = ret.decode('utf-8') bytearraymemoryview :轉化為字符組 進行節(jié)省內存的切片操作
ord:字符按照unicode轉數(shù)字
chr:數(shù)字按照unicode轉字符
ascii:字符串轉ascaii
repr:用于%r格式化輸出? 大白話就是保留原始輸入的數(shù)據(jù)類型,不會進行任何改變
5.數(shù)據(jù)集合:包括字典dict()和集合()? 和??frozenset()轉變?yōu)椴豢勺兊募?/span>
字典:dict 用于構建字典
集合:set() 函數(shù)創(chuàng)建一個無序不重復元素集,可進行關系測試,刪除重復數(shù)據(jù),還可以計算交集、差集、并集等。
x = set('runoob')? y = set('google')? print(x,y) 刪除重復原素? 還可以進行 交并差集計算
frozenset():轉變?yōu)椴豢勺兊募??? 這種方法去掉了刪除功能
frozenset() 返回一個凍結的集合,凍結后集合不能再添加或刪除任何元素。
?
6.相關內置函數(shù)
len:計算數(shù)據(jù)長度? 字典根據(jù)一對是一個值 來計算
enumerate:enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標,一般用在 for 循環(huán)當中。
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) # 小標從 1 開始 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]普通的 for 循環(huán) >>>i = 0 >>> seq = ['one', 'two', 'three'] >>> for element in seq: ... print i, seq[i] ... i +=1 ... 0 one 1 two 2 threefor 循環(huán)使用 enumerate >>>seq = ['one', 'two', 'three'] >>> for i, element in enumerate(seq): ... print i, seq[i] ... 0 one 1 two 2 three >>> enumerateall:判斷 是否有bool值為fales的值? 只要有一個不是真就返回fales
?? any:判斷 是否有bool值為True的值? 只要有一個是真就返回True
?? zip:zip() 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。如果各個迭代器的元素個數(shù)不一致,則返回列表長度與最短的對象相同 ? 通俗理解就是兩個元素相加得到相對應的列表中的元組集合
?匿名函數(shù)
lambda表達式應用
?
Python中的lambda表達式就是匿名函數(shù),也就是沒有名字的函數(shù)。lambda表達式的語法非常簡單:
?
?
下圖是定義lambda表達式和定義一個普通函數(shù)的對比:
?
?
lambda表達式通常是配合其他的內置函數(shù)一起使用,以達到簡化代碼使代碼邏輯更清晰的目的。
?
注意:
?
使用lambda表達式并不能提高代碼的運行效率,它只能讓你的代碼看起來簡潔一些。
?
對于簡單的函數(shù),也存在一種簡便的表示方式,即:lambda表達式
#普通函數(shù)1 def func(a): 2 return a+1 3 print 'test1_func0:',func(1000)
4
#lambda表達式 5 func0 = lambda a:a+1 6 print 'test2_func0:',func0(1000)
上面這種方法,都實現(xiàn)了將1000+1的結果打印出來這個功能,但是用下面
lambda存在意義就是對簡單函數(shù)的簡潔表示。
說道lambda,這里再贈送一些可以給lambda加buff小伙伴:
1.map函數(shù),我們使用map函數(shù)將會對列表中的所有元素進行操作。map有兩個參數(shù)(函數(shù),列表),它會在內部遍歷列表中的每一個元素,執(zhí)行傳遞過來的函數(shù)參數(shù)。在輸出到新列表中。
1 li = [11, 22, 33] 2 new_list = map(lambda a: a + 100, li)輸出:[111, 122, 133]
當然,map還可以完成多個數(shù)組的相加:
1 li = [11, 22, 33] 2 sl = [1, 2, 3] 3 new_list = map(lambda a, b: a + b, li, sl) 4 print new_list輸出:[12, 24, 36]
2.reduce函數(shù),對于序列內所有元素進行累計操作:
1 lst = [11,22,33] 2 func2 = reduce(lambda arg1,arg2:arg1+arg2,lst) 3 print 'func2:',func2輸出:func2: 66
3.filter函數(shù),他可以根據(jù)條件對數(shù)據(jù)進行過濾:
1 li = [11, 22, 33] 2 new_list = filter(lambda arg: arg > 22, li)3 print new_list
輸出:[33]
轉載于:https://www.cnblogs.com/zgd1234/p/7490590.html
總結
以上是生活随笔為你收集整理的Python全栈之路系列----之-----内置函数和匿名函数lamdba的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 羊大师羊奶可以美容吗?可以用来做面膜吗?
- 下一篇: 悟空机器人换了手机,没办法绑定。手机号码