map() 函数
功能:map主要作用是求一个序列或者多个序列进行函数映射之后的值。
格式:map(function,iterable1,iterable2)
function中参数值可以是一个,也可以是多个;后面的iterable代表function运算中的参数值,有几个参数值就传入几个iterable。
注意:1.迭代器需要进行列表转换 2.map中如果传入的序列长度不一,会依据最短的序列计算
#匿名函数
x=[1,2,3,4]
y=[3,4,6,8,8]
print(list(map(lambda x,y:(x*y)+2,x,y)))
#输出:[5, 10, 20, 34]
filter() 函数:
功能:filter主要作用是过滤掉序列中不符合函数条件的元素,当序列中要删、减元素时,可以使用filter函数。
格式:fliter(function,sequence)
function可以是匿名函数或者自定义函数,它可以对后面的sequence序列的每个元素判定是否符合条件,返回True或者False,从而留下True的元素;sequence可以是列表、元组或者字符串。
注意:迭代器需要进行列表转换
#匿名函数
import random
allNum = []
for i in range(9):
allNum.append(random.randint(1,20))
print(allNum)
print(list(filter(lambda x:x%3,allNum)))
#输出:
#[8, 8, 9, 5, 4, 11, 19, 12, 1]
#[8, 8, 5, 4, 11, 19, 1]
reduce() 函数:
功能:reduce是对一个序列进行压缩运算,得到一个值。
格式:reduce(function,iterable)
function中必须传入两个参数,iterable可以是列表或者元组。
注意:reduce使用前需要导包 from functools import reduce,map和filter是内置函数,所以可以直接调用.
#匿名函数
from functools import reduce
x=[3,4,6,8,8]
print(reduce(lambda x,y:(x+y),x))
#输出:29
nums = [5, 9, 1, 3, 7, 8, 6, 2, 4]
# x = []
# for num in nums:
# if not num % 2:
# x.append(num)
# print(x)
# def test(element):
# return not element % 2
# list((1,2,3)) ==> [1,2,3]
# result = list(filter(test, nums))
result = list(filter(lambda element: not element % 2, nums))
print(result)
nums = [1, 2, 3, 4, 5, 6]
# a = []
# for num in nums:
# a.append(num**2)
# print(a)
# def fn(element):
# return element ** 2
result = list(map(lambda element: element ** 2, nums))
print(result)
print('-' * 29)
# def foo(a, b):
# print('a ====={},b====={}'.format(a, b))
# return a + b
print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5, 6]))
def bar(x, y):
print('x==={},y==={}'.format(x, y))
return x + y['age']
# print(reduce(bar, persons))
# print(reduce(lambda x, y: x['age'] + y['age'] if isinstance(x, dict) else x + y['age'], persons))
print(reduce(bar, persons, 0))