map, reduce和filter

      map可以用于对可遍历结构的每个元素执行同样的操作,批量操作:

map(lambda x: x**2, [1, 2, 3, 4])                 # [1, 4, 9, 16]

map(lambda x, y: x + y, [1, 2, 3], [5, 6, 7])   # [6, 8, 10]

       reduce则是对可遍历结构的元素按顺序进行两个输入参数的操作,并且每次的结果保存作为下次操作的第一个输入参数,还没有遍历的元素作为第二个输入参数。这样的结果就是把一串可遍历的值,减少(reduce)成一个对象:

reduce(lambda x, y: x + y, [1, 2, 3, 4])    # ((1+2)+3)+4=10

       filter根据条件对可遍历结构进行筛选:

data = [randint(-10, 10) for _ in range(10)]
print(data)
result = filter(lambda x: x > 0, data)
print(list(result))
-------------------结果------------------------
[-1, 1, 3, 8, -10, 7, 5, -5, 0, 7]
[1, 3, 8, 7, 5, 7]

  求交集

    s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
    s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
    s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
    print(list(map(dict.keys, [s1, s2, s3])))
    print(reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3])))

 

        

posted on 2022-03-15 22:48  溪水静幽  阅读(51)  评论(0)    收藏  举报