简介:Python内置函数中有不少实用的函数,如:filter、map、reduce、zip,非常好用。
filter: filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
语法:
filter(function, iterable)
参数:
function: 判断函数
iterable: 可迭代对象
返回值:
返回列表
map: map()会根据提供的函数对指定序列做映射。
语法:
map(function, iterable, ...)
参数:
function: 函数
iterable: 一个或多个序列
返回值:
Python 2.x 返回列表
Python 3.x 返回迭代器
reduce: reduce()函数会对参数序列中元素进行累积。Python3.x reduce() 已经被移到 functools 模块里,如果我们要使用,需要引入 functools 模块来调用 reduce() 函数:
语法:
reduce(function, iterable[, initializer])
参数:
function:函数,有两个参数
iterable:可迭代对象
initializer:可选,初始参数
返回值:
返回函数计算结果
zip: zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
语法:
zip([iterable, ...])
参数:
iterabl:一个或多个迭代器;
返回值:
元组列表。
案例源码:
# -*- coding: utf-8 -*-
# time: 2022/5/30 14:07
# file: functionMethods.py
# author: tom
# 公众号: 玩转测试开发
from functools import reduce
def odd_number(x):
return x % 2 == 1
def square(x):
return x ** 2
def multiply(x, y):
return x * y
# filter: 过滤器
new_list10 = list(filter(odd_number, [1, 2, 3, 4, 5]))
new_list11 = list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5]))
new_list12 = list(filter(lambda x: x > 3, [1, 2, 3, 4, 5]))
print(new_list10) # [1, 3, 5]
print(new_list11) # [1, 3, 5]
print(new_list12) # [4, 5]
# map: 映射
new_list20 = list(map(square, [1, 2, 3, 4, 5]))
new_list21 = list(map(lambda x: x > 3, [1, 2, 3, 4, 5]))
new_list22 = list(map(lambda x, y, z: x + y + z, [1, 2], [2, 3], [3, 4])) # 3 个列表,对相同位置的列表数据进行相加
print(new_list20) # [1, 4, 9, 16, 25]
print(new_list21) # [False, False, False, True, True]
print(new_list22) # [6, 9]
# reduce: 对参数迭代器中的元素进行累积
new_list30 = reduce(multiply, [1, 2, 3])
new_list31 = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
new_list32 = reduce(lambda x, y: x + y, ["a1", "b2", "c3"])
print(new_list30) # 6
print(new_list31) # 15
print(new_list32) # a1b2c3
# zip: 打包聚合. *zip函数:会把zip聚合的之后的聚合在一起的几个元素以数组的形式返回
new_list40 = list(zip(("a", "b", "c"), [1, 2, 3]))
new_dict41 = dict(zip(("a", "b", "c"), [1, 2, 3]))
new_dict42 = dict(zip(("a", "b", "c"), [1, 2]))
print(new_list40) # [('a', 1), ('b', 2), ('c', 3)]
print(new_dict41) # {'a': 1, 'b': 2, 'c': 3}
print(new_dict42) # {'a': 1, 'b': 2} 取短进行打包聚合
# *zip() 函数是zip()函数的逆过程,将zip对象变成原先组合前的数据。
a1, a2 = zip(*zip(("a", "b", "c"), [1, 2, 3]))
print(a1) # ('a', 'b', 'c')
print(a2) # (1, 2, 3)
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!