-1

I creating a program for assemble methods testing and I have quite a lot of value assigns that are quite the same but names of the values differ. I want to make my code shorter and a bit easier to read and I am wondering how can I create variables with different names in which I assign some values to them in a for loop.

For example I have something like this:

a_scores = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)
e_scores = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)
p_scores = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)
r_scores = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)
f1_scores = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)
gmean_scores = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)

I was thinking of creating a list of names like this:

scores = ['a_scores', 'e_scores', 'p_scores', 'r_scores', 'f1_scores', 'gmean_scores']

and then create a for loop where I assign np.zeros to them. I was thinking of using dictionary but I am not sure if I implement it correctly. a_scores is not defined and I cnt find it

d = {}
for x in enumerate(scores):
    d[scores[x]] = np.zeros(shape=(n_datasets, n_splits * n_repeats, n_clfs), dtype=float)
print(a_scores)
S0ul3r
  • 149
  • 1
  • 8
  • 1
    Don't create variable variables. Use a dictionary - `scores = {}; scores['p'] = ...` – matszwecja May 12 '22 at 08:54
  • 2
    I didn't understand what you don't like about your solution with the dictionary? The issue there is that you need to do `print(d['a_scores'])` instead of `print(a_scores)`. – user2246849 May 12 '22 at 08:56
  • so later on if I want to use that variable I need to as d['a_scores'] so for example: ```a_mean_scores = np.mean(d['a_scores'], axis=1)``` I just want to re-use those variables later on I am just unsure how will I refer to them – S0ul3r May 12 '22 at 08:59
  • Yes. You can shorten that by using `d['a']` instead of the unnecessarily verbose `d['a_scores']`… – deceze May 12 '22 at 09:01
  • you could declare them all in a one-liner: `a_scores, e_scores, p_scores, r_scores, f1_scores, gmean_scores = (np.zeros(...) for _ in range(6))` – Anentropic May 12 '22 at 09:15

0 Answers0