“`”

 

<h4>内置函数:map、reduce、filter的用法和区别</h4>

<strong>map</strong>:根据函数对指定序列做映射

<pre><code>map
参数
接收两个参数:一个是函数,一个是序列(可迭代对象)
返回值
Python2 返回列表
Python3 返回迭代器

# 例子:
# abs() 函数返回数字的绝对值
# 新的内容的个数等于原内容的个数
# ret = map(abs,[-1,-5,6,-7])
# print(list(ret))
# [1, 5, 6, 7]
</code></pre>

<strong><em>*filter*</em>:</strong>过滤函数 新的内容少于等于原内容的时候。才能使用filter

<pre><code>filter() 函数用于过滤序列,过滤不符合条件的元素,返回由符合条件元素组成的心列表

参数:
function 函数
iterable 可迭代对象
返回值:
返回列表

# 筛选大于10的数
def is_odd(x):
if x>10:
return True

ret = filter(is_odd,[1,4,5,7,8,9,76]) # 为迭代器
print(list(ret))
# [76]
</code></pre>

<strong>reduce</strong>:对于序列内所有元素进行累计操作

<pre><code>'''
reduce() 函数
reduce() 函数会对参数序列中元素进行累积
函数将一个数据集合(链表、元组等)中的所有数据进行下列操作
'''

from functools import reduce
def add(x,y):
return x + y

print(reduce(add,[1,2,3,4,5]))
# 15

print(reduce(lambda x, y: x+y, [1,2,3,4,5])) # 15

print(reduce(add,range(1,101)))
# 5050
</code></pre>

 

 

 

<pre><code> "“`

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.