Python补遗(三)——map zip filter reduce函数的使用
- map函数是Python内置的高级函数,质如其名,是对一个或多个可迭代序列结构按照某种函数规则进行映射从而形成一个新序列的过程。map函数接受一个规则函数和一个不定长的可迭代对象作为输入,输出一个包含结果的迭代器对象,并且这个迭代器是新的,不会对作为输入的iterables参数产生影响。
- 其函数签名如下:
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函数测试示例
"""
from collections import Iterator
def square(x):
return x**2
input_data = [1,2,3,4,5]
output_data = map(square,input_data)
print(input_data)
print(output_data)
print(isinstance(output_data,Iterator))
print(list(output_data))
print("-------------SPLIT LINE---------------")
"""
在map中使用lambda匿名函数会更加方便,以下例说明:
lambda匿名函数描述了两数相加的规则,map则会取出传入的两个可迭代序列中的相应元素进行lambda规定的操作
这种操作类似于Numpy中的向量化运算规则
"""
print(
list(
map(lambda x,y:x+y,
[1,2,3,4,5],range(5,0,-1)
)
)
)
[1, 2, 3, 4, 5]
<map object at 0x000002BBE79F1320>
True
[1, 4, 9, 16, 25]
-------------SPLIT LINE---------------
[6, 6, 6, 6, 6]
- zip函数接收一个不定长可迭代序列作为输入,输出一个迭代器对象,其中的第一项为各个可迭代序列中的第一项依次组成的元组,其余各项以此类推…,到各个迭代对象中最短的那个迭代完即停止;
- 其函数签名为:
zip(iter1 [,iter2 [...]]) --> zip object
- 其文档字符串为:
Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
代码示例
"""
zip函数测试
"""
result = zip(
[1,2,3,4,5],
(1,2,3,4,5),
"hello"
)
print(isinstance(result,Iterator))
print(list(result))
"""
若是这多个可迭代序列被放在一个大的容器对象如列表中,那么也可以使用*对其进行解包
这对任何接受不定长参数作为输入的函数都是适用的
"""
content = [
[1,2,3,4,5],
(1,2,3,4,5),
"hello"
]
print(
list(
zip(*content)
)
)
True
[(1, 1, 'h'), (2, 2, 'e'), (3, 3, 'l'), (4, 4, 'l'), (5, 5, 'o')]
[(1, 1, 'h'), (2, 2, 'e'), (3, 3, 'l'), (4, 4, 'l'), (5, 5, 'o')]
- filter函数用作按某种操作过滤某个可迭代序列中的一部分值并且以迭代器的形式返回另一部分,其参数结构与map函数相似,function是过滤的规则,但是仅仅接收一个可迭代序列作为其第二个输入参数;
- 其函数签名为:
filter(function or None, iterable) --> filter object
- 其文档字符串为:
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
代码示例
"""
filter函数测试:
filter函数会将序列中的每个值迭代取出后投入到lambda函数中进行计算,
当返回结果为True时保留该数作为输出,
当为False时则将该数进行过滤
"""
result = filter(
lambda x:x>5,
[10,8,4,7,5,1,-1]
)
print(isinstance(result,Iterator))
print(list(result))
True
[10, 8, 7]
- reduce并非Python的内置函数,而是在functools内置库中。该函数提供数据的"归化聚合"功能,也就是当需要对某个可迭代序列中的所有数据进行某种类型的"累计"操作,并最终"聚合"为一个值时,可以使用reduce函数。
- 其函数签名为:
reduce(function, sequence[, initial]) -> value
- 其文档签名为:
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
代码示例
"""
reduce函数测试:
当第三个参数inital为默认的空值时,reduce函数从列表对象的前两个数进行归化;
当initia参数不为空时,reduce函数的归化从initial和列表的第一个数开始
"""
from functools import reduce
result = reduce(lambda x,y:x+y,
[1,2,3,4,5]
)
print(result)
print("-----------SPLIT LINE-------------")
result1 = reduce(lambda x,y:x+y,
[1,2,3,4,5],1
)
print(result1)
15
-----------SPLIT LINE-------------
16
综合案例
班上43个考生的某次考试成绩由于某种原因产生统计错误,所有的偶数成绩都必须在此基础上加一分才能变成正确分数。现在,班主任已经统计出了错误的考试成绩,并且按语文数学英语科学进行了分科统计。请你将分数进行纠正并且计算出每个同学的总分并且按总分从高到低排序:
"""
模拟数据,在[50,100]内取4*43的二维数组模拟43个同学的4门课程成绩
"""
import numpy as np
scores = np.random.randint(50,101,size=(4,43))
print(scores)
"""
使用zip函数将分数由按学科分类变成按学生分类
"""
print("----------------SPLIT LINE-------------------")
scores = list(zip(*scores))
print(list(scores))
print("----------------SPLIT LINE-------------------")
"""
使用map函数将所有成绩进行纠正
"""
map_scores = []
for score in scores:
map_scores.append(
list(map(lambda x:x+1 if x%2==0 else x,score)
)
)
print(map_scores)
print("----------------SPLIT LINE-------------------")
"""
用reduce函数将每个学生的分数进行求和归化
"""
score_result = []
for score in map_scores:
score_result.append(reduce(lambda x,y:x+y,score))
print(score_result)
print("----------------SPLIT LINE-------------------")
print("最终排名:")
print(sorted(score_result,reverse=True))
[[ 74 62 71 76 87 91 51 87 62 90 58 93 69 61 92 88 54 83
91 85 60 65 74 78 70 78 79 59 63 59 85 53 83 53 88 76
98 72 90 74 92 61 66]
[ 83 67 57 57 93 95 88 78 63 97 71 52 91 82 95 70 84 80
84 55 97 69 61 76 66 58 92 50 63 87 75 59 79 53 98 58
79 70 60 59 76 75 99]
[ 61 75 96 68 96 96 99 51 81 68 66 59 65 61 67 88 65 79
74 53 74 88 79 86 83 99 84 62 100 73 90 94 64 63 93 67
72 81 81 80 69 66 64]
[ 61 65 54 67 52 56 85 99 58 80 74 99 96 53 80 77 50 89
57 81 60 89 98 87 58 99 61 94 51 63 91 51 81 77 70 75
67 79 92 80 52 56 94]]
----------------SPLIT LINE-------------------
[(74, 83, 61, 61), (62, 67, 75, 65), (71, 57, 96, 54), (76, 57, 68, 67), (87, 93, 96, 52), (91, 95, 96, 56), (51, 88, 99, 85), (87, 78, 51, 99), (62, 63, 81, 58), (90, 97, 68, 80), (58, 71, 66, 74), (93, 52, 59, 99), (69, 91, 65, 96), (61, 82, 61, 53), (92, 95, 67, 80), (88, 70, 88, 77), (54, 84, 65, 50), (83, 80, 79, 89), (91, 84, 74, 57), (85, 55, 53, 81), (60, 97, 74, 60), (65, 69, 88, 89), (74, 61, 79, 98), (78, 76, 86, 87), (70, 66, 83, 58), (78, 58, 99, 99), (79, 92, 84, 61), (59, 50, 62, 94), (63, 63, 100, 51), (59, 87, 73, 63), (85, 75, 90, 91), (53, 59, 94, 51), (83, 79, 64, 81), (53, 53, 63, 77), (88, 98, 93, 70), (76, 58, 67, 75), (98, 79, 72, 67), (72, 70, 81, 79), (90, 60, 81, 92), (74, 59, 80, 80), (92, 76, 69, 52), (61, 75, 66, 56), (66, 99, 64, 94)]
----------------SPLIT LINE-------------------
[[75, 83, 61, 61], [63, 67, 75, 65], [71, 57, 97, 55], [77, 57, 69, 67], [87, 93, 97, 53], [91, 95, 97, 57], [51, 89, 99, 85], [87, 79, 51, 99], [63, 63, 81, 59], [91, 97, 69, 81], [59, 71, 67, 75], [93, 53, 59, 99], [69, 91, 65, 97], [61, 83, 61, 53], [93, 95, 67, 81], [89, 71, 89, 77], [55, 85, 65, 51], [83, 81, 79, 89], [91, 85, 75, 57], [85, 55, 53, 81], [61, 97, 75, 61], [65, 69, 89, 89], [75, 61, 79, 99], [79, 77, 87, 87], [71, 67, 83, 59], [79, 59, 99, 99], [79, 93, 85, 61], [59, 51, 63, 95], [63, 63, 101, 51], [59, 87, 73, 63], [85, 75, 91, 91], [53, 59, 95, 51], [83, 79, 65, 81], [53, 53, 63, 77], [89, 99, 93, 71], [77, 59, 67, 75], [99, 79, 73, 67], [73, 71, 81, 79], [91, 61, 81, 93], [75, 59, 81, 81], [93, 77, 69, 53], [61, 75, 67, 57], [67, 99, 65, 95]]
----------------SPLIT LINE-------------------
[280, 270, 280, 270, 330, 340, 324, 316, 266, 338, 272, 304, 322, 258, 336, 326, 256, 332, 308, 274, 294, 312, 314, 330, 280, 336, 318, 268, 278, 282, 342, 258, 308, 246, 352, 278, 318, 304, 326, 296, 292, 260, 326]
----------------SPLIT LINE-------------------
最终排名:
[352, 342, 340, 338, 336, 336, 332, 330, 330, 326, 326, 326, 324, 322, 318, 318, 316, 314, 312, 308, 308, 304, 304, 296, 294, 292, 282, 280, 280, 280, 278, 278, 274, 272, 270, 270, 268, 266, 260, 258, 258, 256, 246]
参考链接: