内置方法mapreducefilter
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了内置方法mapreducefilter相关的知识,希望对你有一定的参考价值。
map:
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.
l1 = [1,2,3,4,5,6,7,8,9] def func(a): return a*10 l2 = map(func,l1) print(l2) # <map object at 0x0000000000A7CB00> 也是一个迭代器 for i in l2: print(i)
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.
from functools import reduce #内置函数reduce需要导入后才能使用。 l1 = [1,2,3,4,5,6,7,8,9] def func(a,b): return a+b l2 = reduce(func,l1) print(l2)
filter:
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.‘‘‘
# 一行代码实现对列表a中的偶数位置的元素进行加3后求和 a = [1,2,3,4,5] l = sum([j+3 for j in list(filter(lambda i:a.index(i)%2 == 0, a))]) #用到了过滤器和匿名函数 print(l)
以上是关于内置方法mapreducefilter的主要内容,如果未能解决你的问题,请参考以下文章
python基础知识--10Lambda匿名函数三元表达式及mapreducefilter