本文介绍了如何用"for"创建变量名?环形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我的头衔可能有些混乱,但是我很难描述我的问题.基本上,我需要创建一堆都等于 0 的变量,并且我想使用 for 循环来执行此操作,因此不必进行硬编码.

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.

问题是每个变量都需要有不同的名称,当我从 for 循环调用数字来创建变量时,它无法识别我想要 中的数字> for 循环.这是一些代码,因此更有意义:

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)

我需要它来创建 box_1 并将其添加到列表中,然后创建 box_2 并将其添加到列表中.只是认为我正在调用变量 box_q ,而不是在 for 循环中调用数字.

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.

推荐答案

动态创建变量是反模式,应避免使用.您实际上需要的是列表:

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])

然后,您可以使用以下语法引用所需的任何元素(例如 box_i ):

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

my_box = box_list[boxes[i]]

这篇关于如何用"for"创建变量名?环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:38