1.定义
1.1 map()
可以处理任何可以迭代的东西,将其中的元素按照序列进行处理,并返回一个列表,返回的列表与原列表一致
1.2 filter()
遍历序列每个元素,判断每个元素得到一个bool值,如果是True,留下来
1.3 reduce()
处理序列,把一个序列进行合并操作
2.用法
2.1 map()
num1 = [1, 2, 5, 10, 6]
# lambda x : x + 1
def add_one(i):
return i + 1
# lambda x : x - 1
def reduce_one(i):
return i - 1
# lambda x : x ** 2
def pf(i):
return i * i
def map_l(func, arr):
lis = []
for i in num1:
num = func(i)
lis.append(num)
return lis
注释:#后面为输出
print(map_l(lambda x: x - 1, num1))#[0,1,4,9,5]
print(map_l(reduce_one, num1))#[0,1,4,9,5]
print(map_l(lambda x: x + 1, num1))#[2,3,6,11,7]
print(map_l(add_one, num1))#[2,3,6,11,7]
print(map_l(lambda x: x ** 2, num1))#[1,4,25,100,36]
print(map_l(pf, num1))#[1,4,25,100,36]
# 终极版
def map_l(func, arr):
lis = []
for i in num1:
num = func(i)
lis.append(num)
return lis
print(map_l(lambda x: x - 1, num1))#[0,1,4,9,5]
res = map(lambda x: x - 1, num1)
print('内置函数处理结果:', res)内置函数处理结果:
# <map object at 0x00000267707C20C8>
print(list(res))#[0, 1, 4, 9, 5]
print(list(map(lambda x: x - 1, num1)))#[0, 1, 4, 9, 5]
# map 前面是方法,后面是可以迭代的对象
msg = 'wang da lian'
res = map(lambda x: x.upper(), msg)
print(list(map(lambda x: x.upper(), msg)))
#['W', 'A', 'N', 'G', ' ', 'D', 'A', ' ', 'L', 'I', 'A', 'N']
输出结果:
D:\anaconda\envs\study\python.exe F:/python文件/集合和函数/map函数.py
[0, 1, 4, 9, 5]
[0, 1, 4, 9, 5]
[2, 3, 6, 11, 7]
[2, 3, 6, 11, 7]
[1, 4, 25, 100, 36]
[1, 4, 25, 100, 36]
[0, 1, 4, 9, 5]
内置函数处理结果: <map object at 0x00000267707C20C8>
[0, 1, 4, 9, 5]
[0, 1, 4, 9, 5]
['W', 'A', 'N', 'G', ' ', 'D', 'A', ' ', 'L', 'I', 'A', 'N']
Process finished with exit code 0
2.2 filter()
movie = ['a_alex', 'a_wang', 'da', 'a_lian', 'ke']
def show_test(arr):
return arr.endswith('a')
def filter_test(func,arr):
list = [ ]
for people in arr:
if not func(people):
list.append(people)
return list
res = filter_test(show_test,movie)
print(res)#['a_alex', 'a_wang', 'a_lian', 'ke']
# 终极版本
def filter_test(func, arr):
ret = []
for people in arr:
if func(people):
ret.append(people)
return ret
res = filter_test(lambda x: x.endswith('a'), movie)
print(res)#['da']
res = filter(lambda x: not x.endswith('a'), movie)
print(list(res))#['a_alex', 'a_wang', 'a_lian', 'ke']
# filter 将一个可迭代的列表进行遍历,
# 然后保存结果为True,或保存结果为False的值
2.3 reduce()
from functools import reduce
num = [1,2,3,4]
# sum = 0
# for i in num:
# sum += i
#
# print(sum)
def multi(x,y):
return x * y
lambda x,y: x * y
def reduce_test(func,n,init = 100):
if init is None:
sum = num.pop(0)
else:
sum = init
for i in n:
sum = func(sum,i)
return sum
print(reduce_test(lambda x,y : x*y,num))#2400
reduce(lambda x,y:x*y,num,5)
print(reduce(lambda x,y:x*y,num,5))#120
people = [{'name':'wang','age':1000},
{'name':'lin','age':100},
{'name':'shi','age':18}]
print(list(filter(lambda p:p['age']>=18,people)))
#[{'name': 'wang', 'age': 1000}, {'name': 'lin', 'age': 100},
# {'name': 'shi', 'age': 18}]