-4

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.

woncheol
  • 15
  • 1
  • 4

3 Answers3

0

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
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
0

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.

woncheol
  • 15
  • 1
  • 4
-1

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)
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Better to add try .. except block to prevent crush in case if variable doesn't exist. – Olvin Roght May 01 '19 at 08:06
  • @OlvinRoght This would swallow an actual error in code. :) So no. Fail early. – Yury Tarabanko May 01 '19 at 08:07
  • @YuryTarabanko It works^^. And I have one more question. I really need help at this point. Please look at under. – woncheol May 01 '19 at 09:23
  • @woncheol You don't need `globals()` when you want to set instance properties. `setattr(self, f'data_{i}', value)` would suffice. https://repl.it/repls/LastingCavernousRuntimeenvironment – Yury Tarabanko May 01 '19 at 13:49