美文网首页
Python中的filter函数与map函数

Python中的filter函数与map函数

作者: Holase | 来源:发表于2017-05-10 15:00 被阅读0次

filter()函数

filter()函数:
<code>filter(function or None, sequence) -> list, tuple, or string</code>

filter函数接受两个参数,第一个参数是一个函数None,第二个参数是一个数组序列
当第一个参数为None时,filter会返回一个迭代器,包含第二个参数数组中所有为True的值,例如'True'、'1'。
如果第一个参数是一个函数,则会吧第二个序列中的值,依次带入到函数,返回输出的True值序列

输出0到10之间的偶数,可以这么写:
<pre>
print(list(filter(lambda x:(x+1)%2,range(1,11))))

[2,4,6,8,10]
</pre>

删除一个序列中的空字符串可以这么写:
<pre>
print list(filter(lambda x:x and x.strip(),['a','s ',' g','w g','r','b','',None]))

['a', 's ', ' g', 'w g', 'r', 'b']
</pre>



map函数

filter()函数:
<code>filter(function or None, sequence) -> list, tuple, or string</code>

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,返回一个新的 list 并返回(map()函数并不会改变原序列)。

在编程语言中,map一般指映射

如果我们需要求一个序列的平方值,可以这样使用map():
<pre>
print list(map(lambda x:x**2,[1,2,3,4,5,6]))

[1,4,9,16,25,36]
</pre>

如果我们需首字母大写的一组字符串的,可以这样使用map():
<pre>
print list(map(lambda x:x.capitalize(),['holase','BILL','john','lUCy']))

['Holase', 'Bill', 'John', 'Lucy']
</pre>

相关文章

网友评论

      本文标题:Python中的filter函数与map函数

      本文链接:https://www.haomeiwen.com/subject/kpnitxtx.html