對于腳本的一部分,我有很長的代碼鏈。例如:
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')
最終,根據這些代碼行,我需要生成一個my_variables可以傳遞給函式的變數 ( )串列。例如:
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]
是否有更有效的方法來B1_2013 = images.select('0_B1') and so on...在第一個代碼示例之后自動生成數百行代碼(例如),以便我可以在第二個代碼示例中自動生成變數串列(例如my_variables = [B1_2013, and so on...]?
uj5u.com熱心網友回復:
只需使用回圈或串列理解來制作一個串列。
my_images = [images.select(f'{i}_B{j}') for i in range(8) for j in range(12)]
uj5u.com熱心網友回復:
在這個用例中,使用 adict來存盤“變數”更可行,動態構建變數不是一個好習慣。下面是一個使用itertools.product它將構建dict具有所需輸出的示例:
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))}
結果:
{'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',
...
}
然后訪問所需的“變數”使用:
>>> images['B3_2014']
'1_B1'
uj5u.com熱心網友回復:
@Barmar 的回答是正確的。如果您想通過執行以下操作來索引變數,您可以擴展他的答案:
my_images = {f'{i}_B{j}':images.select(f'{i}_B{j}') for i in range(8) for j in range(12)}
這稱為字典理解。
uj5u.com熱心網友回復:
或字典理解:
my_images = {'B{j}_{2013 i}': images.select(f'{i}_B{j}') for i in range(8) for j in range(12)}
參考他們:
my_images['B1_2013']
my_images['B2_2013']
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354222.html
上一篇:Taskkill使用WMIC和環境變數存在于特定路徑中的行程
下一篇:如何對作為變數子字串的數字求和?
