0

I'm checking some averages for different categories

cat_1 = []

for i, j, k in zip(is, js, ks):    
    if i == 1:
        cat_1.append(i)

avg_cat_1 = stats.mean(cat_1)
print("Avg for cat_1:", avg_cat_1)

If I want to include multiple categories I would like to avoid having to write a new line for each new category.

For the initialization of the lists I could do something like this:

for i in range(nr of categories): 
    a = "cat_%s" % (i)
    print (a)

but that of course only prints me a line and doesnt execute one and for the if statements thats even more complicated.

I wonder if there is a way to just do a loop like this:

for i in range(nr of categories): 
    cat_i = []

or

for i in range(nr of categories): 
    cat_%s = [] %(i)

where the "i" gets recognized not as part of the variable string but as the temporary loop variable and just produces a executable line of code and not just a print out

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Sungod3k
  • 73
  • 1
  • 9

2 Answers2

0

There is a way to lookup variables by name. Say for global variables:

globals()[f'cat_{i}'] = 9

But that is convoluted. Given the limited info, your use case is the textbook use case of a lists of lists:

for i in range(num_of_categories):
    cat[i].append(some_operation(i))
Shoonya
  • 118
  • 8
0

You could use a dictionary, for example:

cat_dict = {'cat_1': cat_1, 'cat_2': cat_2, 'cat_3': cat_3, ... }
for i in range(1, number_of_categories + 1):
    cat_dict['cat_%s' % i] = []

There's also the NOT recommended way: you could use exec

for i in range(1, number_of_categories + 1):
    exec('cat_%s = []' % i)

One very simple reason this is bad is clarity. If a user wants to see where the variable cat_3 is created, they might search the file for cat_3, but it won't be found at this point.

For a list of reasons that this is poor practice, see Why is using 'eval' a bad practice?

Cory Nezin
  • 1,551
  • 10
  • 22