python map和filter函数

知道python有这几个内置方法,但一直以来用的都不多,最近重新看了一下,重新记录一下。

map()会根据提供的函数对指定序列进行映射,python3会返回一个迭代器,具体用法如下:

def double(x):
    return 2*x

if __name__=="__main__":
    print(map(double,[1,2,3,4,5]))
    print()
    for i in map(double,[1,2,3,4,5]):
        print(i)

  运行结果:

F:devpythonpython.exe F:/pyCharm/L02_Test/L02Interface/L02_Common/try_demo.py
<map object at 0x000002A3D91A3EF0>

2
4
6
8
10

Process finished with exit code 0

  filter()内置函数用于过滤序列,用于过滤不符合条件的元素,返回符合条件的元素的列表,python3返回一个迭代器。

def is_odd(x):
    return x%2==0

if __name__=="__main__":
    print(filter(is_odd,[1,2,3,4,5,6,7,8,9,10]))
    print()
    for i in filter(is_odd,[1,2,3,4,5,6,7,8,9,10]):
        print(i)

  运行结果:

F:devpythonpython.exe F:/pyCharm/L02_Test/L02Interface/L02_Common/try_demo.py
<filter object at 0x000001C75D243FD0>

2
4
6
8
10

Process finished with exit code 0

  

原文地址:https://www.cnblogs.com/linwenbin/p/11960143.html