对于字典'dict1'中的变量'a'和'b',以后是否可以使用'dict1'中给出的键调用变量'a'来为其赋值?
a=""
b=""
dict1= {0:a,1:b}
dict1[0] = "Hai" #assign a value to the variable using the key
print(a) #later call the variable```
对于字典'dict1'中的变量'a'和'b',以后是否可以使用'dict1'中给出的键调用变量'a'来为其赋值?
a=""
b=""
dict1= {0:a,1:b}
dict1[0] = "Hai" #assign a value to the variable using the key
print(a) #later call the variable```
不,当您进行赋值 {key:value} 时,该值不会引用原始变量,因此改变其中一个不会影响另一个。
该变量不会自动设置,您可以做的是:
def update_dic(a,b):
dict1={0:a, 1:b}
return dict1
def update_vars(dict1):
return dict1[0],dict1[1]
每次你调用第一个函数时,你的字典都会更新,第二次你总是得到 a 和 b 回来。
我们可以通过使用两个具有相同数量变量的字典来做到这一点:
这允许使用键“0”访问变量“a”,然后使用“dict2”更改其值,然后通过调用“a”获取值。
但是请记住,变量需要写成字符串,即用引号括起来,当用作常规变量时它不起作用。
dict1= {0:'a',1:'b'}
dict2={'a':'x','b':'y'}
dict2[dict1[0]]="Hai" #assign a value to the variable using the key
print(dict2['a']) #later call the variable ````
您可以使用类来存储变量和索引字典来执行类似的操作:
class Variables():
def __init__(self):
self.varIndex = dict()
def __getitem__(self,index):
return self.__dict__[self.varIndex[index]]
def __setitem__(self,index,value):
self.__dict__[self.varIndex[index]] = value
variables = Variables()
variables.a = 3
variables.b = 4
variables.varIndex = {0:"a",1:"b"}
variables[0] = 8
print(variables.a) # 8