Python : pass variable name as argument

后端 未结 4 1308
渐次进展
渐次进展 2021-01-16 12:22

I have a function f(x) in which many local variables are created. x is a string with the same name as one of these local variables and I would like

4条回答
  •  孤独总比滥情好
    2021-01-16 12:41

    You can use exec() and put your code in argument as a string

    def f(x):
        a = [1,2,3]
        b = [2,3,4]
        c = [3,4,5]
        exec(x + "[0] = 10")
    
        return a,b,c
    
    print f("a")
    # ([10, 2, 3], [2, 3, 4], [3, 4, 5])
    

提交回复
热议问题