首页 > 代码库 > 内置方法map、reduce、filter
内置方法map、reduce、filter
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)
内置方法map、reduce、filter
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。