python中 filter $ map 函数

2019年7月13日

python中filter & maph函数

  1. filter函数

filter()函数用于过滤序列,过滤掉不符合条件的元素,Python3以后返回一个迭代器对象(可以用list()转化为列表查看)。filter()函数接受两个参数,第一个为函数或者None,第二个为序列。如果第一个参数是函数,则把序列里的每一个元素传到函数里进行判断,返回True的元素被放到新的列表中。
如果第一个参数是None,则返回序列中为True的元素。

#求列表中的所有奇数
def Odd(num): 
    return num % 2

odd_L = filter(Odd,range(10))
print(odd_L) #返回迭代器对象
print(list(odd_L) #通过内置函数list()将其转换成列表输出
print(odd_L):

<filter object at 0x000002144ECD6128>

print(list(odd_L)):

[1,3,5,7,9]


  1. map函数

map()函数根据提供函数对指定序列做映射。
map()函数接受两个参数,第一个为函数,第二个为序列,同filter一样返回一个迭代器对象。

def pow(num):
    return num**2
pow_L = map(pow,[1,2,3])
print(list(pow_L))
print(list(pow_L))

[1,4,9]

posted @ 2019-07-20 17:02  why72  阅读(276)  评论(0编辑  收藏  举报