1. 程式人生 > >python 學習彙總52:迭代器常用內建函式map,filter,zip,reduce(入門學習- tcy)

python 學習彙總52:迭代器常用內建函式map,filter,zip,reduce(入門學習- tcy)

迭代器常用內建函式 2018/9/15

1.內建函式

map(function, iterA, iterB, ...) ->iterator #建立迭代器等同於itertools.starmap();
filter(function,iterable) ->iterator #建立迭代器等同於非itertools.filterfalse();
zip(iterable, iterA, iterB, ...) ->iterator #建立迭代器等同於itertools.zip_longest();
functools.reduce(fun, sequence[, initial]) -> value #fun(x,y)計算結果和下一個元素用作函式引數

2.1.map(函式,Iterable)
將傳入函式作用到序列每個元素,結果作為新Iterator返回:

# 例項1
def func(x):
return x * x

lst = [1, 2, 3, 4, 5];L = []
a = map(func, lst)  # Iterator
print(list(a))  # [1, 4, 9, 16, 25]

for i in [1, 2, 3, 4, 5]:
L.append(func(i))
print(L)  # [1, 4, 9, 16, 25]

a1 = map(func, [i for i in range(1, 6)])
a2 = map(lambda x: x * x, [i for i in range(1, 6)])
print(list(a1), list(a2))  #a2=a1=[1, 4, 9, 16, 25]

# 例項2
def upper(s):
return s.upper()

a3 = list(map(upper, ['Tom', 'Mark']))  # ['TOM', 'MARK']
a4 = [upper(s) for s in ['Tom', 'Mark']] # ['TOM', 'MARK']

 2.2.filter(函式,序列)
用於過濾序列。返回的是一個Iterator:

# 傳入函式依次作用於每個元素根據返回值True保留該元素

# 例項1
def is_odd(n):
return n % 2 ==  1

lst = range(0, 10)
a1 = list(filter(is_odd, lst))  # [1, 3, 5, 7, 9]
a2 = list(x for x in lst if is_odd(x))  # [1, 3, 5, 7, 9]
a3 = list(filter(lambda x: x % 2 == 1, lst))  # [1, 5, 9, 15]

def not_empty(s): # 序列中空字串刪掉:
return s and s.strip()

lst = ['A', '', 'B', None, 'C', ' ']
str1 = list(filter(not_empty, lst))  # ['A', 'B', 'C']
str2 = list(filter(lambda s: s and s.strip(), lst)) # ['A', 'B', 'C']

 2.3.zip(iterA, iterB, ...) 從每個迭代中取一個元素並將它們返回到一個元組中:

a1=zip(['a', 'b', 'c'], (1, 2, 3))  #list(a1); [('a', 1), ('b', 2), ('c', 3)]
a2=zip(['a', 'b'], (1, 2, 3)) #list(s2); [('a', 1), ('b', 2)]

 2.4.reduce(函式,Iterable)用法
把一個函式作用在一個序列上,reduce把結果繼續和序列的下一個元素做
累積計算原理:reduce(f, [x1, x2, x3, x4]) = f( f( f(x1, x2), x3) , x4)

# 例項1:序列求和
from functools import reduce

def add(x, y):
return x + y

lst=[1, 3, 5, 7, 9]
a1=reduce(add,lst )  #25
a2=reduce(lambda x,y:x+y,lst)  #25
a3=reduce(lambda x,y:x+y,lst,100)  #125

# 例項2:序列變換成整數
def fn(x, y):
return x * 10 + y
def char_to_num(s):#str轉int
return int(s)

a1=reduce(fn, [1, 3, 5, 7, 9])  #13579
a2=reduce(fn, map(char_to_num, '13579'))#13579
a3=reduce(lambda x, y: x * 10 + y, map(char_to_num, '13579'))#13579

# 例項3-元素中間新增符號
a1=reduce(lambda a, b: '{}:{}'.format(a, b), lst)  # 1:3:5:7:9
a2=reduce(lambda a, b: '{}0x{}\\'.format(a, b),lst,"\\")  #\0x1\0x3\0x5\0x7\0x9\