2015-10-27 37 views
0

我以前从未使用Python,但已决定通过操纵一些市场数据开始学习它。我无法使用字典结构。在该命令下面read_arr_pricedict_price_recalc [price_id] [year_to_index(年),Q] =浮子(LINE2)的代码/7.5分配浮子(LINE2)/7.5到所有阵列,不论其price_id联系。我想知道是不是因为我没有正确初始化dict_priceFor循环使用字典关键引用不起作用

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 

我很感谢你能提供任何指针。

+0

你的缩进不适合'read_dict_price' –

+0

对,对不起。现在更正。 – KHH

+0

'dict_price_recalc = dict_price'这会将相同的字典赋予另一个变量,它不会复制字典。改用'dict_price_recalc = dict_price.copy()'。 – multivac

回答

2

此行price_id[key] = np_array正在为每个键设置相同的数组,因此每个键都指向相同的数组。你的意思可能是price_id[key] = np_array.copy()

+0

是的,当我第一次开始使用它时,发现这是一个奇怪的numpy特征。这样做的理念是什么?笨重的一种。 – jh44tx

+0

它不仅适用于numpy,它的属性几乎适用于任何非简单(列表,字典等)对象,因为实际上,该变量是对该数据的引用,很像c指针。 '.copy()'创建一个具有完全相同值的对象的新实例,而不是只将变量指向同一个实例 –

+1

了解可变对象和不可变对象之间的区别很重要。在一次的几个地方有一个可变对象(列表,字典等)是非常有用的。 – hpaulj