Python:在for循环中声明变量,每个变量都有不同的变量名

Python: Declaring variables in for loop, each with different variable name

本问题已经有最佳答案,请猛点这里访问。

我有一个代码需要声明几个类属性,如下所示。但是,如果我有100个分子,我需要复制粘贴代码,并手动更改100次数字吗?或者,是否有一种方法可以根据for循环计数器声明具有不同名称的变量?例如

1
2
For i in range(100):
    self.features_str(i+1)x_a= ...

快速解释每个函数的作用。Tensorise_Smiles返回3个张量(以ndarray的形式)特性_to_listedtuple接受张量和另一个Ndarray并返回一个Ndarray。

我要做的是为每个分子创建一个属性3次,原子、键和边的特征。但是,问题是如果有许多分子,我必须复制和粘贴代码很多次,将1X更改为2X,3X,…,100X,…。等等。有更好的方法吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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)

谢谢您!


你可以使用setattr。

1
2
for i in range(100):
    setattr(self,"features_str{}x_a".format(i), value)

但是,我会考虑使用字典来存储所有数据。例如:

1
2
3
4
d = {}
for i in range(100):
    d["{}x_a".format(i)] = value
self.features = d

这允许您遍历所有特性,对它们进行排序等。