我以前從未使用Python,但已決定通過操縱一些市場數據開始學習它。我無法使用字典結構。在該命令下面read_arr_pricedict_price_recalc [price_id] [year_to_index(年),Q] =浮子(LINE2)的代碼/7.5分配浮子(LINE2)/7.5到所有陣列,不論其price_id聯繫。我想知道是不是因爲我沒有正確初始化dict_price。For循環使用字典關鍵引用不起作用
def read_dict_price(dat_filename, dict_price):
## Load data set
dat_file = open(dat_filename,'r')
## Copy arr_price
dict_price_recalc = dict_price
## Iterate through each row in the data set, assigning values to variables
for line in dat_file:
year = int(line[11:15])
price_id = line[0:4]
Q = 0
Q1 = line[19:21]
Q2 = line[23:25]
Q3 = line[27:29]
Q4 = line[31:33]
## Truncate year_list to prepare for another run of the nested loop
year_list = []
year_list[:] = []
## Repopulate
year_list = [Q1, Q2, Q3, Q4]
#### This is where the mistake happens ####
## Iterate through each row in year_list, populating dict_price_recalc with price data
for line2 in year_list:
dict_price_recalc[price_id][year_to_index(year), Q] = float(line2)/7.5
Q += 1
return dict_price_recalc
我的代碼初始化dict_price低於:
def init_dict_price(dat_filename):
price_id= {}
dat_file = open(dat_filename,'r')
np_array = np.zeros(shape=(100,4)) # Zeros as placeholders
np_array[:] = np.NaN
for line in dat_file:
key = line[:11]
price_id[key] = np_array
return price_id
我很感謝你能提供任何指針。
你的縮進不適合'read_dict_price' –
對,對不起。現在更正。 – KHH
'dict_price_recalc = dict_price'這會將相同的字典賦予另一個變量,它不會複製字典。改用'dict_price_recalc = dict_price.copy()'。 – multivac