【问题标题】:python: badly behaving dict inside a function- erroneous TypeErrorpython:在函数中表现不佳的 dict - 错误的 TypeError
【发布时间】:2014-12-14 05:06:32
【问题描述】:

我有需要清理的字典,例如

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.ndarraynew_dict[key]new_dict[key][new_dict[key_string]&lt;limit]

但是,当我运行 clean_high() 时,我得到了错误:

TypeError:只有一个元素的整数数组可以转换为索引

什么?

clean_high() 内部,new_dict[key] 的类型是字符串,而不是数组。 为什么类型会改变?有没有更好的方法来修改我的字典?

【问题讨论】:

  • 您能否提供一个工作示例,其中包含一些示例数据以及完整的错误跟踪?
  • 你传递给clean_high(...)的参数是什么?此外,每个传感器的阵列是否具有相同的形状(每个传感器在同一天进行测量)?如果某一天的某个传感器出现问题,您想从所有传感器中删除该天的值吗?

标签: python python-2.7 numpy dictionary typeerror


【解决方案1】:

在迭代字典时不要修改它。根据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

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 2023-03-21
    • 2013-01-15
    • 2021-08-09
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多