2024-04-25 12:12:41 发布
网友
对于字典“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}时,该值不引用原始变量,因此对其中一个变量进行变异不会影响另一个变量
您可以使用类来存储变量和索引字典,执行类似的操作:
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
变量不是自动设置的,您可以做的是:
def update_dic(a,b): dict1={0:a, 1:b} return dict1 def update_vars(dict1): return dict1[0],dict1[1]
每次调用第一个函数时,您的字典都会得到更新,第二次总是会得到a和b
不,在执行赋值{key:value}时,该值不引用原始变量,因此对其中一个变量进行变异不会影响另一个变量
您可以使用类来存储变量和索引字典,执行类似的操作:
变量不是自动设置的,您可以做的是:
每次调用第一个函数时,您的字典都会得到更新,第二次总是会得到a和b
相关问题 更多 >
编程相关推荐