如何通过与其相同名称的变量访问已存在的数组并更新它

0 投票
1 回答
39 浏览
提问于 2025-04-12 04:07

我在程序的早些时候声明了一个数组,然后把一个变量赋值给了这个数组的名字。后来,我试图用我声明的变量名来改变数组中的一个值,但数组并没有更新。

 J2 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] #i defined the array J2.
appointment = 'J2' # then i declared the variable appointment to the string J2
time = 3 # and i assigned the variable time=3. 
appointment[time] = 6 #i tried to input 6 into the J2 at index 3 by typing appointment[time]=6 

但是当我打印数组 J2 时,我发现数组的内容一直没有变化。

1 个回答

-1

当你用一个字符串来指代一个变量名时,它并不会直接访问那个变量。相反,你可以使用一个字典来存储你的数组,并把它们和对应的名字关联起来。

试试这个:

解决方案 1:

J2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
arrays = {'J2': J2}
appointment = 'J2'

# Assign the variable time=3
time = 3

# Update the value in the array using the dictionary
arrays[appointment][time] = 6

print(arrays['J2'])

输出:

[0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

解决方案 2 (根据评论中的建议):

J2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

appointment = 'J2'

time = 3

# Update the value in the array using globals()
globals()[appointment][time] = 6

print(J2)

输出:

[0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

撰写回答