如何在循环中使用i进行变化?

时间:2019-05-01 07:50:21

标签: python

如何更改此代码

train_0.append(0)
train_1.append(1)
train_2.append(2)
train_3.append(3)

像下面一样使用循环吗?

for i in range(4):
    train_i.append(i)

我的代码出现此错误。

NameError: name 'train_i' is not defined

谢谢。

3 个答案:

答案 0 :(得分:0)

有一些方法可以做到这一点,但是通常情况下,例如问题定义了错误的代码...最好使用代码来做一些事情,并将大量变量隐瞒为可迭代的事情。

有一些方法:

for i in range(4):
    train = globals().get("train_{}".format(i), None)
    if train:
        train.append(i)

for i in range(4):
    try:
        eval("train_{0}.append({0})".format(i))
    except:
        pass

答案 1 :(得分:0)

在课堂上,要定义self.variance,我该如何调整您的解决方案?

for i in range(4):
        globals()["test_{}".format(i)].append(ToTensor(vectors[i]))

因为较高的代码在您的帮助下起作用。

但是在情况下(在课堂上)它不起作用。

class MyDataset():
    def __init__(self, cropped_img_vectors, targets):
        self.data_0 = cropped_img_vectors[0]
        self.data_1 = cropped_img_vectors[1]
        self.data_2 = cropped_img_vectors[2]
        self.data_3 = cropped_img_vectors[3]
        self.targets = targets

    def __getitem__(self, index):
        data_0 = self.data_0[index]
        data_1 = self.data_1[index]
        data_2 = self.data_2[index]
        data_3 = self.data_3[index]
        y = self.targets[index]
        dataset = []
        for i in range(4):
            dataset.append(["data_{}".format(i)])
        return dataset, y

    def __len__(self):
        return len(self.data_0)

我将uppder更改为以下。

class MyDataset():
    def __init__(self, cropped_1pixel_dataset, targets):
        for i in range(4):
            globals()["self.data_{}".format(i)] = cropped_1pixel_dataset[i]
        self.targets = targets

    def __getitem__(self, index):
        for i in range(4):
            globals()["data_{}".format(i)] = cropped_1pixel_dataset[i][index]
        y = self.targets[index]
        return [globals()["data_{}".format(i)] for i in range(4)], y

    def __len__(self):
        return len(self.data_0)

运行此单元格后,

MyDataset(train_cropped_1pixel_dataset, train_dataset.targets)

发生此错误。

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-960ee70394c1> in <module>
      3 train_loader = torch.utils.data.DataLoader(dataset = train_dataset,
      4                                            batch_size = batch_size,
----> 5                                            shuffle = True)

~/.local/lib/python3.5/site-packages/torch/utils/data/dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn)
    800             if sampler is None:
    801                 if shuffle:
--> 802                     sampler = RandomSampler(dataset)
    803                 else:
    804                     sampler = SequentialSampler(dataset)

~/.local/lib/python3.5/site-packages/torch/utils/data/sampler.py in __init__(self, data_source, replacement, num_samples)
     58 
     59         if self.num_samples is None:
---> 60             self.num_samples = len(self.data_source)
     61 
     62         if not isinstance(self.num_samples, int) or self.num_samples <= 0:

<ipython-input-10-293dc919d173> in __len__(self)
     12 
     13     def __len__(self):
---> 14         return len(self.data_0)

AttributeError: 'MyDataset' object has no attribute 'data_0'

我真的需要帮助。 谢谢。

答案 2 :(得分:-1)

假设您已在全局范围内定义了所有train_<i>变量,则可以通过globals()访问它们。 Demo

train_0 = []
train_1 = []
train_2 = []
train_3 = []


for i in range(4):
    globals()[f'train_{i}'].append(i)

print(train_0, train_1, train_2, train_3)