【发布时间】:2019-06-28 13:00:37
【问题描述】:
我有一个包含多个变量的类,我想随机选择其中一个变量并进行更改。为了挑选我的变量,我使用了每个类实例都有一个 dictionary 和 random 包这一事实;
import random as rnd
import chromosome as Chromosome
instance1 = Chromosome() #creates class instance
random_key = rnd.choice([instance1.__dict__]) #picks out random key
instance1.random_key = 5 #change the value of the random key
最后一行显然不起作用,但我想知道是否有任何方法可以获得该功能?我尝试使用格式功能,但没有奏效。
另一种解决方案可能是挑选一个介于 0 到我的字典长度之间的随机数。我可以手动写出我想做的每个变量更改,但只根据随机数更改其中一个,它可能看起来像这样;
import random as rnd
import chromosome as Chromosome
instance1 = Chromosome() #creates class instance
which_var_to_change = rnd.randint(1,len(instance1.__dict__)) #the for loop below works as if the length is 2
counter = 1
for key, value in instance1.__dict__.items():
if key == 'first_variable' and counter > which_var_to_change:
instance1.first_variable = 5 #change the value of the random key
if key == 'second_variable' and counter > which_var_to_change:
instance1.second_variable = 5 #change the value of the random key
counter += 1
这个解决方案的问题是,如果我有太多变量,它会变得非常混乱。
【问题讨论】:
标签: python-3.x random instance-variables