我有一个代码需要声明几个类属性,如下所示。但是,如果我有100个分子,我是否需要复制并粘贴代码并相应地手动更改数字100次?还是有一种方法可以根据for循环计数器声明具有不同名称的变量?例如
For i in range(100):
self.features_str(i+1)x_a= ...
每个功能的简要说明。 tensorise_smiles返回3个张量(以ndarray的形式) features_to_listedtuple接收张量和另一个ndarray并返回一个ndarray。
我要做的是为每个分子创建3次原子,键和边缘特征的属性。但是,问题是如果有很多分子,我必须多次复制和粘贴代码,将1x更改为2x,3x,...,100x等。有更好的方法吗?
# Setting up features_d. Features containing SMILES for solvent, ligand, RA
self.features_d_a = features_d
# 1,2,3 represents the molecule for the solvent, ligand, RA. x,y,z for atom, bond, edge tensor
self.features_1x_a, self.features_1y_a, self.features_1z_a = tensorise_smiles(features_d[:, 0])
self.features_2x_a, self.features_2y_a, self.features_2z_a = tensorise_smiles(features_d[:, 1])
self.features_3x_a, self.features_3y_a, self.features_3z_a = tensorise_smiles(features_d[:, 2])
self.features_1x_a = features_to_listedtuple(self.features_1x_a, labels)
self.features_1y_a = features_to_listedtuple(self.features_1y_a, labels)
self.features_1z_a = features_to_listedtuple(self.features_1z_a, labels)
self.features_2x_a = features_to_listedtuple(self.features_2x_a, labels)
self.features_2y_a = features_to_listedtuple(self.features_2y_a, labels)
self.features_2z_a = features_to_listedtuple(self.features_2z_a, labels)
self.features_3x_a = features_to_listedtuple(self.features_3x_a, labels)
self.features_3y_a = features_to_listedtuple(self.features_3y_a, labels)
self.features_3z_a = features_to_listedtuple(self.features_3z_a, labels)
谢谢!
答案 0 :(得分:2)
您可以使用setattr。
for i in range(100):
setattr(self, "features_str{}x_a".format(i), value)
但是,我会考虑使用字典来存储所有数据。例如:
d = {}
for i in range(100):
d["{}x_a".format(i)] = value
self.features = d
这允许您迭代所有功能,对其进行排序等。