Home > Back-end >  Automatically pass variables names to list
Automatically pass variables names to list

Time:11-09

I have a long chain of code for a portion of a script. For example:

B1_2013 = images.select('0_B1')
B2_2013 = images.select('0_B2')
B3_2013 = images.select('0_B3')
B4_2013 = images.select('0_B4')
B5_2013 = images.select('0_B5')
B6_2013 = images.select('0_B6')
B7_2013 = images.select('0_B7')
B8_2013 = images.select('0_B8')
B9_2013 = images.select('0_B9')
B10_2013 = images.select('0_B10')
B11_2013 = images.select('0_B11')
B1_2014 = images.select('1_B1')
B2_2014 = images.select('1_B2')
B3_2014 = images.select('1_B3')
B4_2014 = images.select('1_B4')
B5_2014 = images.select('1_B5')
B6_2014 = images.select('1_B6')
B7_2014 = images.select('1_B7')
B8_2014 = images.select('1_B8')
B9_2014 = images.select('1_B9')
B10_2014 = images.select('1_B10')
B11_2014 = images.select('1_B11')

and so on ...

B11_2020 = images.select('7_B11')

Ultimately, from these lines of code, I need to generate a list of variables (my_variables) that I can pass off to a function. For example:

my_variables = [B1_2013, B2_2013, B3_2013, B4_2013, B5_2013, B6_2013, B7_2013, B8_2013, B9_2013, B10_2013, B11_2013, \
                B1_2014, B2_2014, B3_2014, B4_2014, B5_2014, B6_2014, B7_2014, B8_2014, B9_2014, B10_2014, B11_2014]

Is there a more efficient approach to automatically generate hundreds of lines of code (e.g. B1_2013 = images.select('0_B1') and so on...) following the first code example so that I can automatically generate a list of variables in the second code example (e.g. my_variables = [B1_2013, and so on...]?

CodePudding user response:

Just make a list using a loop or list comprehension.

my_images = [images.select(f'{i}_B{j}') for i in range(8) for j in range(12)]

CodePudding user response:

@Barmar's answer is correct. You can extend his answer if you wanted to index the variables by doing the following:

my_images = {f'{i}_B{j}':images.select(f'{i}_B{j}') for i in range(8) for j in range(12)}

This is called dictionary comprehension.

CodePudding user response:

Or dictionary comprehension:

my_images = {'B{j}_{2013   i}': images.select(f'{i}_B{j}') for i in range(8) for j in range(12)}

Refer them with:

my_images['B1_2013']
my_images['B2_2013']
...

CodePudding user response:

In this use case it is more viable to use a dict to store the "variables" it is not good practice to dynamically build variables. Below is an example using itertools.product that will build a dict with desired output:

from itertools import product

images = {f'B{i}_{y 2013}': images.select(f'{y}_B{i}')
          for y, i in product(range(12), range(1, 8))}

Result:

{'B1_2013': '0_B1',
 'B2_2013': '0_B2',
 'B3_2013': '0_B3',
 'B4_2013': '0_B4',
 'B5_2013': '0_B5',
 'B6_2013': '0_B6',
 'B7_2013': '0_B7',
 'B1_2014': '1_B1',
 'B2_2014': '1_B2',
 'B3_2014': '1_B3',
 ...
}

Then to access the desired "variable" use:

>>> images['B3_2014']
'1_B1'
  • Related