1

I have a list of categories [A, B] and I want to Define multiple variables using a string for loop which is [A, B]. I was able to do it manually, however, it is not efficient especially if you have more than 2 categories. Could you please help me solve this issue? here is what i did

RGB_A = []
for i in range(1,numGeoPics+1):
    g = gs.DataFile ('Outdir/Filters/RGB/addcoord_A{}.out'.format (i))['value']
    RGB_A.append (g)

RGB_B = []
for i in range(1,numGeoPics+1):
    g = gs.DataFile ('Outdir/Filters/RGB/addcoord_B{}.out'.format (i))['value']
    RGB_B.append (g)

and here is what I want to do :

Categories = ['A','B']
for Category in Categories: 
    RGB_['Category'] (here how to loop over categories list ?) = []
    for i in range(1,numGeoPics+1):
         g = gs.DataFile ('Outdir/Filters/RGB/addcoord_'+ str(Category)  +'{}.out'.format (i))['value']
         RGB_['Category'] (here how to loop over categories list ?).append (g)
  • Any reason you can't use a dictionary, or just not store the variables at all and just use a list? – Mous Jun 08 '22 at 21:26

1 Answers1

1

Use a dictionary to map the categories to variables.

categories = {'A': RGB_A, 'B': RGB_B}
for category, RGB in categories.items():    # .items() on a dictionary loops over the key and value together
    for i in range(1, numGeoPics + 1):
        g = gs.DataFile(f'Outdir/Filters/RGB/addcoord_{category}{i}.out')['value']
        RGB.append(g)
  • Got the idea thanks , however it says invalid syntax let me try again – Karim_Mokdad_1995 Jun 08 '22 at 21:35
  • @Karim_Mokdad_1995 put your new code and the traceback for the error in your original post so we can see – thisismy-stackoverflow Jun 08 '22 at 21:38
  • `categories = {'A': RGB_A, 'B': RGB_B} for category, RGB in categories.items(): # .items() on a dictionary loops over the key and value together for i in range(1, numGeoPics + 1): g = gs.DataFile(f'Outdir/Filters/RGB/addcoord_{category}{i}.out')['value'] RGB.append(g)` – Karim_Mokdad_1995 Jun 08 '22 at 21:44
  • and the error is NameError: name 'RGB_A' is not defined – Karim_Mokdad_1995 Jun 08 '22 at 21:44
  • 1
    @Karim_Mokdad_1995 well you still have to define RGB_A and RGB_B beforehand if you want to use them in the dictionary. Alternatively you can create lists right there in the dictionary like Mous mentioned, and only access them through the dictionary: `categories = {'A': [], 'B': []}` – thisismy-stackoverflow Jun 08 '22 at 22:03
  • 1
    Another thing I'd note is that you might not even need to name them `RGB_A` and `RGB_B` if it's sequential. Just make a list of what would be the values of that dict. – Mous Jun 08 '22 at 22:58