如何用“for”循环创建变量名?

2024-03-29 11:55:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我的标题可能有些混乱,但我在描述我的问题时遇到了困难。基本上,我需要创建一组变量,它们都等于0,我想用一个for循环来完成这项工作,这样就不必硬编码了。

问题是每个变量都需要有一个不同的名称,当我从我的for循环中调用数字来创建变量时,它无法识别我想要的是for循环中的数字。下面是一些代码,这样更合理:

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循环中的数字。


Tags: 代码in名称box标题编码列表for
3条回答

动态创建变量是一个anti-pattern,应该避免。你需要的是一个list

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

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

my_box = box_list[boxes[i]]

你可以用字典。在我看来,这种方法更好,因为您可以看到密钥和值对。

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}

看起来您试图使用q的值编辑box_q中的“q”,但是qbox_q是两个完全不同的变量。

您可以动态地操作变量名,但在Python中很少这样做。很好的解释:https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html

相反,您可以使用列表并使用列表索引访问项目,例如

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

您可以使用box_list[0]box_list[1]等访问每个项。您还可以更简洁地创建框:

boxes = [0] * total_squares

如果希望框中包含某些内容并具有此命名结构,则可以使用字典:

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

这将创建一个具有total_squares键值对的字典。您可以使用boxes_dict['box_0']boxes_dict['box_1']等访问每个框。您甚至可以将值从0更改为将某些内容放入框中,例如

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

相关问题 更多 >