How to create variable names with a “for” loop? [duplicate]

天大地大妈咪最大 提交于 2021-02-04 06:45:48

问题


I know my title may be somewhat confusing, but I had trouble describing my issue. Basically, I need to create a bunch of variables that all equal 0, and I want to do this with a for loop so I don't have to hard code it.

The problem is each variable needs to have a different name and when I call the number from my for loop to create the variable, it doesn't recognize that I want the number from the for loop. Here is some code so that makes more sense:

total_squares = 8
box_list = []
for q in range(total_squares):
  box_q = 0
  box_list.append(box_q)

I need it to create box_1 and add that to the list, then create box_2, and add that to the list. Just it thinks I'm calling a variable box_q, rather than calling the number in the for loop.


回答1:


Creating variables dynamically is an anti-pattern and should be avoided. What you need is actually a list:

total_squares = 8
box_list = []
boxes = [0] * total_squares
for q in range(total_squares):
  box_list.append(boxes[q])

Then you can refer to any element you want (say, box_i) using the following syntax:

my_box = box_list[boxes[i]]



回答2:


It looks like you're trying to use the value of q to edit the 'q' in box_q, but q and box_q are two completely different variables.

You can manipulate variable names dynamically, but this is very rarely done in Python. Good explanation here: https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html

Instead, you can use a list and access the items using list indexing, e.g.

total_squares = 8
box_list = []
for q in range(total_squares):
    box_list.append(0)

You access each item with box_list[0], box_list[1], etc. You can also create your boxes more succinctly:

boxes = [0] * total_squares

If you want your boxes to contain something, and have this naming structure, then you could use a dictionary:

boxes_dict = {'box_{}'.format(q): 0 for q in range(total_squares)}

This creates a dictionary with total_squares key-value pairs. You can access each box using boxes_dict['box_0'], boxes_dict['box_1'], etc. You can even change the values from 0 to put something in the box, e.g.

boxes_dict['box_2'] = "Don't use dynamic variable naming"
boxes_dict['box_3'] = 'And number your boxes 0, 1, 2 ... etc'



回答3:


You can use dictionary. This approach is better in my opinion as you can see the the key and value pair.

code

total_squares=8
box_list={}
for q in range(total_squares):
    box_list['box_'+str(q)]=0

print(box_list)

output

{'box_0': 0, 'box_1': 0, 'box_2': 0, 'box_3': 0, 'box_4': 0, 'box_5': 0, 'box_6': 0, 'box_7': 0}


来源:https://stackoverflow.com/questions/53509989/how-to-create-variable-names-with-a-for-loop

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