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

前端 未结 7 1827
夕颜
夕颜 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条回答
  •  猫巷女王i
    2020-11-22 09:15

    One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional package (https://pypi.org/project/PyFunctional/). Here's a comparison of the two:

    flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}
    

    PyFunctional version

    Very legible syntax. You can say:

    "I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."

    from functional import seq  # PyFunctional package to allow easier syntax
    
    def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
        return seq(flight_destinations_dict.items()) \
            .map(lambda x: x[0] if city in x[1] else []) \
            .filter(lambda x: x != []) \
    

    Default Python version

    It's all backwards. You need to say:

    "OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."

    def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
        return list(
            filter(lambda x: x != [],
                   map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
                   )
        )
    

提交回复
热议问题