python之路——內置函數與匿名函數

內置函數python

     python裏的內置函數。截止到python版本3.6.2,如今python一共爲咱們提供了68個內置函數。它們就是python提供給你直接能夠拿來使用的全部函數。這些函數有些咱們已經用過了,有些咱們還沒用到過,還有一些是被封印了,必須等咱們學了新知識才能解開封印的。那今天咱們就一塊兒來認識一下python的內置函數。這麼多函數,咱們該從何學起呢?程序員

上面就是內置函數的表,68個函數都在這兒了。這個表的順序是按照首字母的排列順序來的,你會發現都混亂的堆在一塊兒。好比,oct和bin和hex都是作進制換算的,可是卻被寫在了三個地方。。。這樣很是不利於你們概括和學習。那我把這些函數分紅了6大類。你看下面這張圖面試

咱們今天就要學習用粉紅色標註出來的這四大塊——56個方法。算法

做用域相關:shell

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

globals()——獲取全局變量的字典數據結構

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

在全局執行這兩種方法,結果相同ide

在局部執行,locals()表示函數內的名字,globals()始終不變函數

 其餘:

字符串類型代碼的執行——eval、exec、compile

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

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

exec()將字符串類型的代碼執行——沒有返回值

print(exec('1+2+3+4'))
exec("print('hello,world')")

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'。

>>> #流程語句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
1
3
5
7
9


>>> #簡單求值表達式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)


>>> #交互語句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #執行前name變量不存在
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> exec(compile3) #執行時顯示交互命令,提示輸入
please input your name:'pythoner'
>>> name #執行後name變量有值
"'pythoner'"

輸入輸出相關:

 input()輸入

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

print()輸出

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    file:  默認是輸出到屏幕,若是設置爲文件句柄,輸出到文件
    sep:   打印多個值之間的分隔符,默認爲空格
    end:   每一次打印的結尾,默認爲換行符
    flush: 當即把內容輸出到流文件,不做緩存
    """
print源碼剖析
f = open('tmp_file','w')
print(123,456,sep=',',file = f,flush=True)

#sep=','  分隔符
file關鍵字的說明
 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 能夠把光標移動到行首但不換行
打印進度條

數據類型相關:

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

內存相關:

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

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

t = (1,2,3)
l = [1,2,3]
print(hash(t))  #可hash
print(hash(l))  #會報錯

'''
結果:
TypeError: unhashable type: 'list'
'''
hash實例

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

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

文件操做相關:

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

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

能夠用encoding指定編碼

#建立文檔並寫入
f=open('print_test','w',encoding='utf-8')
print(121421313,file=f)
建立文檔並寫入

模塊操做相關:

__import__導入一個模塊

import time
導入模塊
os = __import__('os')
print(os.path.abspath('.'))
__import__

幫助:

help() 看一些幫助的信息   退出輸入quit

和調用相關:

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

若是n是一個函數名,就會返回Ture

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

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

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

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

和數字相關:

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

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

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

和數據結構相關:

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

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

 

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

序列:reversed,slice

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

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

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

filter

filter()函數接收一個函數 f 和一個list,這個函數 f 的做用是對每一個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。

例如,要從一個list [1, 4, 6, 7, 9, 12, 17]中刪除偶數,保留奇數,首先,要編寫一個判斷奇數的函數:

def is_odd(x):
    return x % 2 == 1

而後,利用filter()過濾掉偶數

>>>filter(is_odd, [1, 4, 6, 7, 9, 12, 17])

結果:

[1, 7, 9, 17]

利用filter(),能夠完成不少有用的功能,例如,刪除 None 或者空字符串:

def is_not_empty(s):
    return s and len(s.strip()) > 0
>>>filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])

結果:

['test', 'str', 'END']

注意: s.strip(rm) 刪除 s 字符串中開頭、結尾處的 rm 序列的字符。

當rm爲空時,默認刪除空白符(包括'\n', '\r', '\t', ' '),以下:

>>> a = ' 123'
>>> a.strip()
'123'



>>> a = '\t\t123\r\n'
>>> a.strip()
'123'

map

Python中的map函數應用於每個可迭代的項,返回的是一個結果list。若是有其餘的可迭代參數傳進來,map函數則會把每個參數都以相應的處理函數進行迭代處理。map()函數接收兩個參數,一個是函數,一個是序列,map將傳入的函數依次做用到序列的每一個元素,並把結果做爲新的list返回。

有一個list, L = [1,2,3,4,5,6,7,8],咱們要將f(x)=x^2做用於這個list上,那麼咱們可使用map函數處理。

>>> L = [1,2,3,4,] 
>>> def pow2(x): 
... return x*x 
... 
>>> map(pow2,L) 
[1, 4, 9, 16] 

sorted

對List、Dict進行排序,Python提供了兩個方法
對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變

--------------------------------sorted---------------------------------------

sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.


-----------------------------------------------------------------------------
參數說明:
iterable:是可迭代類型;
key:傳入一個函數名,函數的參數是可迭代類型中的每一項,根據函數的返回值大小排序;
reverse:排序規則. reverse = True  降序 或者 reverse = False 升序,有默認值。
返回值:是一個通過排序的可迭代類型,與iterable同樣。
 
例:
列表按照其中每個值的絕對值排序

 

l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
列表按照絕對值順序

列表按照每個元素的len排序

 

l = [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))
列表按照每個元素的長度排序

 匿名函數:

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

 

#這段代碼
def calc(n):
    return n**n
print(calc(10))
 
#換成匿名函數
calc = lambda n:n**n
print(calc(10))

 

上面是咱們對calc這個匿名函數的分析,下面給出了一個關於匿名函數格式的說明

函數名 = lambda 參數 :返回值

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

咱們能夠看出,匿名函數並非真的不能有名字。

匿名函數的調用和正常的調用也沒有什麼分別。 就是 函數名(參數) 就能夠了~~~

練一練:

請把如下函數變成匿名函數
def add(x,y):
    return x+y

上面是匿名函數的函數用法。除此以外,匿名函數也不是浪得虛名,它真的能夠匿名。在和其餘功能函數合做的時候

l=[3,2,100,999,213,1111,31121,333]
print(max(l))

dic={'k1':10,'k2':100,'k3':30}


print(max(dic))
print(dic[max(dic,key=lambda k:dic[k])])
res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)

輸出
1
25
49
16
64
res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
    print(i)

輸出
11
15

面試題:

現有兩個元組(('a'),('b')),(('c'),('d')),請使用python中匿名函數生成列表[{'a':'c'},{'b':'d'}]

#答案一
test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
print(test(t1,t2))
#答案二
print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))
#還能夠這樣寫
print([{i:j} for i,j in zip(t1,t2)])
答案
1.下面程序的輸出結果是:
d = lambda p:p*2
t = lambda p:p*3
x = 2
x = d(x)
x = t(x)
x = d(x)
print x

#答案:
def multipliers():
    new_l = []
    for i in range(4):
        def func(x):
            return x*i
        new_l.append(func)
    return new_l
    return [lambda x: i * x for i in range(4)]  #6,6,6,6
for func in multipliers():
    func(2)
print([m(2) for m in multipliers()])


2.現有兩元組(('a'),('b')),(('c'),('d')),請使用python中匿名函數生成列表[{'a':'c'},{'b':'d'}]

答案:
(1)
t1 = (('a'),('b'))
t2 = (('c'),('d'))
for i in zip(t1,t2):
    print(i)
test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
print(test(t1,t2))
(2print(list(map(lambda t:{t[0]:t[1]} ,zip(t1,t2))))
(3print([{i[0]:i[1]} for i in zip(t1,t2)])
3.如下代碼的輸出是什麼?請給出答案並解釋。
def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])
請修改multipliers的定義來產生指望的結果。
#答:
def multipliers():
    new_l = []
    for i in range(4):
        def func(x):
            return x*i
        new_l.append(func)
    return new_l
    # return [lambda x: i * x for i in range(4)]  #6,6,6,6
# i = 0
# [func]
# i = 1
# [func,func]
# i = 2
# [func,func,func]
# i = 3
# [func,func,func,func]
    #
# for func in multipliers():
#     func(2)
print([m(2) for m in multipliers()])
練習

 

本章小結

說學習內置函數,不如說整理本身的知識體系。其實整理這些內置函數的過程也是在整理本身的知識體系。

咱們講課的時候會歸類:經常使用或者不經常使用,主要仍是根據場景而言。

一個優秀的程序員就應該是在該用這個方法的時候信手拈來,把每個內置的函數都用的恰到好處。

要想作到這一點,至少要先了解,才能在須要的時候想起,進而將它用在該用的地方。

可是在這裏,我仍是以本身的一點經驗之談,把幾個平時工做中相對更經常使用的方法推薦一下,請務必重點掌握:

其餘: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

相關文章
相關標籤/搜索