我有一個陣列 (oned_2018),我想要一個函式來制作這個陣列的多個副本。副本數是這個陣列中的最大值。例如最大的是6;那么應該有6份。有人可以幫我寫這個回圈嗎? 我想要類似...
for i in range(1, max(oned_2018) 1):
classi_20 = oned_2018.copy() # of course this line is incorrect!
和輸出應該像這個手動作業:
class1_20 = oned_2018.copy()
class2_20 = oned_2018.copy()
class3_20 = oned_2018.copy()
class4_20 = oned_2018.copy()
class5_20 = oned_2018.copy()
class6_20 = oned_2018.copy()
uj5u.com熱心網友回復:
如果你真的想這樣做,你可以使用globals():
oned_2018 = [1, 2, 3, 4]
for i in range(1, max(oned_2018) 1):
globals()[f"class{i}_20"] = oned_2018.copy() # of course this line is incorrect!
print(class1_20) # [1, 2, 3, 4]
但是通常避免動態創建這樣的變數。通常人們會推薦使用 dict 代替:
oned_2018 = [1, 2, 3, 4]
data = {f"class{i 1}_20": oned_2018.copy() for i in range(max(oned_2018))}
print(data['class1_20']) # [1, 2, 3, 4]
uj5u.com熱心網友回復:
我建議您使用字典,而不是通過變數命名它們:
classes_to_data = {}
for i in range(1, max(oned_2018) 1):
classes_to_data[i] = oned_2018.copy()
然后,您可以按如下方式訪問它們:
classes_to_data[1] # outputs what you named 'class1_20'
classes_to_data[2] # outputs what you named 'class2_20'
# and so on...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/335723.html
