Python: Using vars() to assign a string to a variable

前端 未结 6 1895
南笙
南笙 2020-11-27 17:09

I find it very useful to be able to create new variables during runtime and create a dictionary of the results for processing later, i.e. writing to a file:

         


        
6条回答
  •  半阙折子戏
    2020-11-27 17:48

    Do this instead. It's simpler.

    myDict = {}
    for i in range (1,10):
        temp = "variable"+str(i) 
        myDict[temp] = myFunctionThatReturnsData() # variable1= data1, variable2 = data2,etc.
    

    That's all you ever need to do.

    The results will be myDict['variable1'] through myDict['variable9']

    You rarely need vars() or locals(). Just stop using them and use ordinary variables and ordinary dictionaries. Try to avoid things you don't understand and stick to the simple, obvious stuff.

提交回复
热议问题