2015-10-27 36 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