python - apply Operation on multiple variables

后端 未结 6 2080
梦谈多话
梦谈多话 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 13:09

    You can use map to apply a function to every element of a list with a lambda function to perform your operation. Then use list unpacking to overwrite values in orginal variables.

    a = 1
    b = 2
    c = 3
    
    a,b,c = list(map(lambda x: x*2, [a,b,c]))
    
    print(a,b,c)
    
    # prints: (2, 4, 6)
    

    map returns a generator, that's why we need to explicit create the list to unpack.

提交回复
热议问题