Python: Change variable suffix with for loop

孤者浪人 提交于 2021-02-04 08:12:30

问题


I know this was asked a lot but I can not work with/understand the answers so far.

I want to change the suffix of variables in a for loop.

I tried all answers the stackoverflow search provides. But it is difficult to understand specific codes the questioner often presents.

So for clarification I use an easy example. This is not meant as application-oriented. I just want to understand how I can change the suffix.

var_1 = 10
var_2 = 100
var_3 = 1000

for i in range(1,4):
    test_i = var_i + 1
    print(test_i)

Expected result: creating and printing variables:

test_1 = 11 
test_2 = 101 
test_3 = 1001


Expected Output

11
101
1001

Error: var_i is read as a variable name without the changes for i.


回答1:


Instead of doing a convoluted naming convention, try to conceive of your problem using a data structure like dictionaries, for example.

var={}
var[1] = 10
var[2] = 100
var[3] = 1000

test={}
for i in range(1,4):
    test[i] = var[i] +1

print(test)

If somehow you are given var_1 etc as input, maybe use .split("_") to retrieve the index number and use that as the dictionary keys (they can be strings or values).


Small explanation about using indexing variable names. If you are starting out learning to program, there are many reasons not to use the eval, exec, or getattr methods. Most simply, it is inefficient, not scalable, and is extremely hard to use anywhere else in the script.

I am not one to insist on "best practices" if there is an easier way to do something, but this is something you will want to learn to avoid. We write programs to avoid having to type things like this.

If you are given that var_2 text as a starting point, then I would use string parsing tools to split and convert the string to values and variable names.

By using a dictionary, you can have 1000 non-consecutive variables and simply loop through them or assign new associations. If you are doing an experiment, for example, and call your values tree_1, tree_10 etc, then you will always be stuck typing out the full variable names in your code rather than simply looping through all the entries in a container called tree.

This is a little related to using a bunch of if:else statements to assign values:

# inefficient way -- avoid
if name == 'var_1' then:
    test_1=11
elif name == 'var_2' then:
    test_2=101

It is so much easier just to say:

test[i]= var[i]+1

and that one line will work for any number of values.




回答2:


I would advise against using eval in 99.99% of all cases. What you could do is use the built-in getattr function:

import sys
var_1 = 10
var_2 = 100
var_3 = 1000

for i in range(1,4):
    test_i = getattr(sys.modules[__name__], f"var_{i}") + 1
    print(test_i)



回答3:


for i in range(1, 4):
   print(eval('var_' + str(i)))

Step by step:

1) Make your variables strings:

stringified_number = str(i)

2) evaluate your expression during runtime:

evaluated_variable = eval('var_' + stringified_number)



来源:https://stackoverflow.com/questions/57546321/python-change-variable-suffix-with-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!