2014-10-18 80 views
3

我有一些需要清理的字符,例如:python:功能錯誤的字典 - 錯誤的TypeError

dict = { 
    'sensor1': [list of numbers from sensor 1 pertaining to measurements on different days], 
    'sensor2': [list of numbers from from sensor 2 pertaining to measurements from different days], 
    etc. } 

有些日子,有不好的價值觀,我想從那個糟糕的一天生成的所有傳感器值的新字典來用鍵的一個值使用的上限被刪除:

def clean_high(dict_name,key_string,limit): 
    '''clean all the keys to eliminate the bad values from the arrays''' 
    new_dict = dict_name 
    for key in new_dict: new_dict[key] = new_dict[key][new_dict[key_string]<limit] 
    return new_dict 

如果我在IPython中單獨運行所有的行,它就可以工作。糟糕的日子被淘汰了,好的日子也被保留下來了。這些類型numpy.ndarray都:new_dict[key]new_dict[key][new_dict[key_string]<limit]

但是,當我運行clean_high(),我得到的錯誤:

TypeError: only integer arrays with one element can be converted to an index

什麼?

clean_high()的內部,new_dict[key]的類型是一個字符串,而不是一個數組。 爲什麼類型會改變?有沒有更好的方法來修改我的字典?

+1

你能否提供一個示例數據的工作示例以及完整的錯誤跟蹤? – 2014-10-18 22:02:15

+0

你傳遞給'clean_high(...)'的參數是什麼?另外,每個傳感器的陣列是否具有相同的形狀(每個傳感器在同一天進行測量)?如果一個傳感器的日子不好,你想從所有傳感器中刪除那天的值? – cm2 2014-10-18 22:03:06

回答

2

迭代時不要修改字典。根據python documentation:「在字典中添加或刪除條目時迭代視圖可能會引發RuntimeError或無法遍歷所有條目」。相反,創建一個新的字典並修改它,同時迭代舊字典。

def clean_high(dict_name,key_string,limit): 
    '''clean all the keys to eliminate the bad values from the arrays''' 
    new_dict = {} 
    for key in dict_name: 
     new_dict[key] = dict_name[key][dict_name[key_string]<limit] 
    return new_dict 
+0

謝謝!這解決了問題! – debara 2015-06-17 18:30:16