Python : pass variable name as argument

后端 未结 4 1265
渐次进展
渐次进展 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])
    
    0 讨论(0)
  • 2021-01-16 12:52

    Use a dict

    Simply, use a dict:

    def f(x):
        values = {
            "a": [1,2,3],
            "b": [2,3,4],
            "c": [3,4,5]
        }
        values[x][0] = 10
        return values["a"], values["b"], values["c"]
    

    If you really really want, use your original code and do locals()[x][0] = 10 but that's not really recommended because you could cause unwanted issues if the argument is the name of some other variable you don't want changed.

    0 讨论(0)
  • 2021-01-16 12:55

    If your input is a string and you want to refer to a variable that matches that string you can use globals() like this:

    globals()['x']
    

    This way you can get the value and/or edit its contents.

    0 讨论(0)
  • 2021-01-16 12:59

    use dictionary like this:

    def f(x):
         d = {"a" :[1,2,3],"b" : [2,3,4],"c" : [3,4,5]}
         d[x][0] = 10
    
         return d
    
    0 讨论(0)
提交回复
热议问题