How can I change this code

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

using loop like under?

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

My code occurs this error.

NameError: name 'train_i' is not defined

Thank you.

3 Answers

-1
Yury Tarabanko On Best Solutions

Provided that you have all train_<i> variables defined in global scope you could access them via 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)
0
Olvin Roght On

There is some methods how to do this, but usually such as problems defines bad code... Better to do something with code and covert big amount of variables to something iterable.

There is some methods:

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
0
woncheol On

In the class, to define self.variance, how I can adjust your solution?

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

Becuase upper code works with your help.

But under case (in class) it doesn't work.

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)

I changed uppder to under.

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)

And after run this cell,

MyDataset(train_cropped_1pixel_dataset, train_dataset.targets)

it occur this error.

---------------------------------------------------------------------------
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'

I really need helps.. Thank you.