一:map():映射
map()函數在python2和python3中是區別的
python2中的定義:映射后,返回一個列表
>>> help(map)
Help on built-in function map in module __builtin__:
map(...)
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence)
python3中的定義:映射后,返回一個迭代器,
>>> help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
map()有兩個參數,一個函數,一個序列,序列中每一個元素都會做為參數傳給前邊的函數,然后生成新的對象(python2中是list,python3中是iterator),第二個參數必須用一個序列:元祖,列表,字符串
python2中的map():
>>> map(str,[1,2,3,4])
['1', '2', '3', '4']
python3中的map():
搭配lambda函數
>>> map(lambda x:x.upper(),"abc")
['A', 'B', 'C']
map()函數搭配lambda傳多個參數
python2:
例子:2個list,[1,2,3][4,5,6],合並為[(1, 4), (2, 5), (3, 6)]
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> map(lambda x,y:(x,y),a,b)
[(1, 4), (2, 5), (3, 6)]
python3:
>>> map(lambda x,y:(x,y),a,b)
<map object at 0x000001FF1FFAEEF0>
>>> type(map(lambda x,y:(x,y),a,b))
<class 'map'>
>>> list(map(lambda x,y:(x,y),a,b))
[(1, 4), (2, 5), (3, 6)]
也可以自己定義函數
map()傳多個參數(序列)時,每次取元素進行map時,是在每個序列的相同位置取值,
然后作為一個元祖傳給參數前邊的函數的,所以用這個原理,把函數設置None,也可以生成題中的結果,由此也能看到map函數在取值時的邏輯
>>> map(None,list1,list2)
[(1, 4), (2, 5), (3, 6)]
或者用zip()函數也可以,zip()函數在python2和python3中也是有區別的
python2中的zip():
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
python3中的zip():
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> zip(a,b)
<zip object at 0x000001FF1FFA2D48>
>>> type(zip(a,b))
<class 'zip'>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6)]
二:lambda匿名函數
lambda語句被用來創建新的函數對象,並且在運行時返回它們。
Python使用lambda關鍵字來創建匿名函數。這種函數得名於省略了用def聲明函數的標准步驟。
lambda只是一個表達式,函數體比def簡單很多
lambda的主體是一個表達式,而不是一個代碼塊。僅僅能在lambda表達式中封裝有限的邏輯進去。
#如下邊例子,x,y,z相當於匿名函數中的參數,x+y+z是函數體,匿名函數的定義賦值給了a,a就是一個函數,可以用a()來調用這個函數
>>> a=lambda x,y,z:x+y+z
>>> a(1,2,3)
6
三:filter()
filter和map的區別是,filter保留函數返回為true的值,不返回的不顯示
map是保留返回的結果,無論返回的是啥,filter會把不滿足true條件的結果忽略掉
例子:刪除字符串中的小寫字母
#encoding=utf-8
def delete_lowercase(s):
if s>='a' and s<='z':
return ""
else:
return s
print map(delete_lowercase,"AABBaabb")
print "".join(map(delete_lowercase,"AABBaabb"))
結果:
D:\>python test.py
['A', 'A', 'B', 'B', '', '', '', '']
AABB
保留數字中大於5的位
#-*-coding:utf-8-
def func(n):
if int(n)>5:
return n
print filter(func,"123467")
#只要return的是True,就會保留
結果:
D:\>python test.py
67
或者一行搞定
>>> filter(lambda x:int(x)>=5,"12345678")
'5678'
filter()根據參數中的序列,返回相同形式的序列,列表返回列表,字符串返回字符串
或者一行搞定
>>> filter(lambda x:int(x)>=5,"12345678")
'5678'
>>> filter(lambda x:int(x)>=5,list("12345678"))
['5', '6', '7', '8']
>>> filter(lambda x:int(x)>=5,"12345678")
'5678'
>>> filter(lambda x:int(x)>=5,tuple("12345678"))
('5', '6', '7', '8')
python3:
>>> filter(lambda x:int(x)>5, "12346789")
<filter object at 0x000001BB7FE7EE48>
>>> list(filter(lambda x:int(x)>5, "12346789"))
['6', '7', '8', '9']
>>> tuple("12345678")
('1', '2', '3', '4', '5', '6', '7', '8')
四:推導列表
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
相當於把for循環中每次循環得到的數作為一個列表的一個元素,知道所有循環執行結束
各個元素生成的過程相當於以下兩句得到的:
for i in range(10):
print i
>>> [i for i in range(10) if i !=5]
[0, 1, 2, 3, 4, 6, 7, 8, 9]
練習:a=[[1,2,3],[4,5,6]]用推導列表生成[[1, 4], [2, 5], [3, 6]]
[[j[i] for j in a] for i in range(3)]
結果:
[[1, 4], [2, 5], [3, 6]]
以上推導列表過程轉換成for循環:最外層的for也對應轉換成for循環的最外層
>>> for i in range(3):
... print "\n**************"
... for j in a:
... print j[i],
...
結果中有三個元素,每個元素又是包含2個元素的列表,這個元素是執行一次for循環得到的值
拆解過程:
每執行一次完整的循環,生成兩個數,這個兩個數會以列表的形式作為最后結果列表的一個元素,
也就是說,推導列表的每一步生成的結果會以列表的形式存在,包括最終的結果
>>> for i in range(3):
... print "\n**************"
... for j in a:
... print j[i],
...。、,
**************
1 4
**************
2 5
**************
3 6
五:reduce()累計操作
Reduce()累計操作,要搭配函數來執行
>>> reduce(lambda x,y:x+y,[1,2,3,4])
10
第一次x=1,y=2, x+y=3,之后x+y的結果3賦值給x,y為3
第二次x=3,y=3,x+y=6,之后x+y的結果6賦值給x,y為4
第三次x=3,y=4,x+y=10
>>> 1:1+2 2:3+3 3:6+4
>>> reduce(lambda x,y:x+y,range(1,101))
5050
>>> reduce(lambda x,y:x+y,[1,2,3])
6
X=1,y=2
結果3傳給x
y從第二次開始存結果
reduce(lambda x,y:x+y+y,[1,2,3])
x=1,y=2,y=2
x=5,y=3,y=3
x+y+y=5+3+3=11
x是5就對了
>>> reduce(lambda x,y:x+x+y,[1,2,3])
x=1,x=1,y=2
x+x+y=1+1+2=4
x=4,x=4,y=3
x+x+y=4+4+3=11
>>> reduce(lambda x,y:x+x+y,['1','2','3'])
x=1,x=1,y=2
x=’112’,x=’112’,y=’3’
x+x+y='1121123'
六:切片,就是數列的切片,比較基本也比較常用
>>> [1,2,3,4,5][3:5]
[4, 5]
練習:用map,lambda,推到列表,正則,join,去掉字符串中的小寫字母
>>> import re
>>> "".join([i for i in map(lambda x:(re.match(r"[A-Z]*",x).group()),"abcABC") if i !=""])
'ABC'
拆解過程:
>>> [i for i in map(lambda x:(re.match(r"[A-Z]*",x).group()),"abcABC") if i !=""]
['A', 'B', 'C']
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i for i in range(10) if i !=5]
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> map(lambda x:(re.match(r"[A-Z]*",x).group()),"abcABC")
['', '', '', 'A', 'B', 'C']
>>> lambda x:(re.match(r"[A-Z]*",x).group())("abcABC")
<function <lambda> at 0x00000000054EDB38>
>>> re.match(r"[A-Z]*","ABC").group()
'ABC'
練習:統計字符串中一共有幾個數字
s="sdfa45ads46723"
#lambda
>>> filter(lambda x:x.isdigit(),list(s))
['4', '5', '4', '6', '7', '2', '3']
>>> len(filter(lambda x:x.isdigit(),list(s)))
7
>>> reduce(lambda x,y:x+y,map(lambda x:x.isdigit(),list("sdfa45ads46723")))
7
>>> reduce(lambda x,y:x+y,map(lambda x:len(x),filter(lambda x:x.isdigit(),[i for i in s][::-1])))
7