我以前从未使用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