自定義函數變量的設置
一個星號
*傳入元組
,且這個變量爲可變變量
兩個星號
**後的那些參數被當做字典
類型傳遞到函數中
帶有雙星號的可變參數只能出現在參數列表的最後
注意雙星號是字典類型(字典形式要有鍵值對)
>>>def d(a,b=6,*c,**d):
print("a=",a,"b=",b,"c=",c,"d=",d)
>>>d(1,2,3,4)
a= 1 b= 2 c= (3, 4) d= {}
>>>def d(a,b=6,*c,**d):
print("a=",a,"b=",b,"c=",c,"d=",d)
>>>d(a=1,b=2,c=3)
a= 1 b= 2 c= () d= {'c': 3}
不能重複賦值
#對b二次賦值報錯
>>>def d(a,b=6,*c,**d):
print("a=",a,"b=",b,"c=",c,"d=",d)
>>>d(1,2,3,4,b=1)
TypeError: d() got multiple values for argument 'b'
強制命名參數
>>>def aaa(*,a,b,c):
return a+b+c
>>>aaa(a=1,b=1,c=1)
3
強制命名必須用命名來傳遞值
>>>def aaa(*,a,b,c):
return a+b+c
>>>aaa(a=1,1,1)
SyntaxError: positional argument follows keyword argument#報錯
lambda匿名函數
函數名 = lambda 參數:表達式
等價於
def 函數名(參數):
函數體
return 返回值
!!! lambda不允許包含複合語句,只可以包含一個表達式
map函數
map(function(函數),iterable,…(一個或多個序列))
>>>def square(x):
return x**2
>>>map(square,[1,2,3,4,5])
# 生成迭代器
<map at 0x2c5f1526860>
需要轉換
>>>def square(x):
return x**2
>>>list(map(square,[1,2,3,4,5]))
[1, 4, 9, 16, 25]
結合lambda
>>>map(lambda x:x**2,[1,2,3,4,5])
<map at 0x2c5f1526cf8>
>>>list(map(lambda x:x**2,[1,2,3,4,5]))
[1, 4, 9, 16, 25]
filter函數
filter(function(判斷函數),iterable(可迭代對象))
留下True,過濾False
判斷函數:只能接受一個參數,且返回值是True或False
可迭代對象:直接調filter函數只返回迭代器,需要用list()或其他函數來轉換,但在for循環中可以直接使用
zip函數
zip(seq[,seq,…])
可把兩個或多個序列中的相應項合併在一起
以元組的格式返回它們
在處理完最短序列中的所有項後停止
>>>a = [1,2,3]
>>>b = [4,5,6]
>>>list(zip(a,b))
#返回元組列表
[(1, 4), (2, 5), (3, 6)]
#返回字典類型
>>>dict(zip([1,2],[3,4]))
{1: 3, 2: 4}
#zip(*...)爲還原
>>>a = [1,2,3]
>>>b = [4,5,6]
>>>list(zip(*zip(a,b)))
[(1, 2, 3), (4, 5, 6)]
enumerate函數
用於將一個可遍歷的數據編號
>>>s = ['a','b','c','d']
>>>list(enumerate(s))
#默認從0開始
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>>list(enumerate(s,start = 1))
#可以設定從1或其他數字開始
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]