How to use filter, map, and reduce in Python 3

前端 未结 7 1695
夕颜
夕颜 2020-11-22 08:27

filter, map, and reduce work perfectly in Python 2. Here is an example:

>>> def f(x):
        return x % 2 !=         


        
7条回答
  •  醉话见心
    2020-11-22 08:59

    As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce in the global namespace.

    A quick implementation might look like this:

    from contextlib import contextmanager    
    
    @contextmanager
    def noiters(*funcs):
        if not funcs: 
            funcs = [map, filter, zip] # etc
        from functools import reduce
        globals()[reduce.__name__] = reduce
        for func in funcs:
            globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
        try:
            yield
        finally:
            del globals()[reduce.__name__]
            for func in funcs: globals()[func.__name__] = func
    

    With a usage that looks like this:

    with noiters(map):
        from operator import add
        print(reduce(add, range(1, 20)))
        print(map(int, ['1', '2']))
    

    Which prints:

    190
    [1, 2]
    

    Just my 2 cents :-)

提交回复
热议问题