python - apply Operation on multiple variables

后端 未结 6 2167
梦谈多话
梦谈多话 2021-01-27 12:26

I know that this is a rather silly question and there are similar ones already answered, but they don\'t quite fit, so... How can I perform the same operation on multiple variab

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-27 12:50

    You can store them in a container, and then use map to apply one function on every element of the container
    For example with a list:

    def function_to_apply(element):
        return element*2
    
    # Define variables and store them in a container
    a,b,c = 1,2,3
    container = (a,b,c)
    
    # Apply the function on every element with map
    container = tuple(map(function_to_apply, container))
    a,b,c = container
    


    This can also be done with lambda functions to avoid defining a new function every time

    # Define variables and store them in a container
    a,b,c = 1,2,3
    container = (a,b,c)
    
    # Apply the function on every element with map
    container = tuple(map(lambda x: x*2, container))
    a,b,c = container
    

    If you have a really large set of variables and you want to retrieve them automatically without having to type each one of them like in a,b,c = container, you can use dict to store them with names or exec function to assign them dynamically.

    map documentation: https://docs.python.org/3/library/functions.html#map
    lambda documentation: https://docs.python.org/3/reference/expressions.html#grammar-token-lambda-expr

提交回复
热议问题