【问题标题】:Subtracting a value from each element in a 2d array within a dictionary从字典中的二维数组中的每个元素中减去一个值
【发布时间】:2026-02-17 10:45:02
【问题描述】:

我正在尝试从字典中的二维数组中的所有值中减去一个值 (dark_val)。目前我正在遍历每个键并将值提取到列表中,然后使用列表理解:

def dark_subtract(dic, dark_val):

    band_values = []

    # loop through the keys and variables to lists
    for key, value in dic.items():
        band_values.append(value)

    band_values[:] = [x - dark_val for x in band_values]

    return band_values

然而,理想情况下,我想在字典中进行迭代,以便返回字典而不是列表(即band_values)。

我尝试了以下方法,它没有出现任何错误,但也没有更改值:

def dark_subtract(dic, dark_val):
    """
    Must be a dictionary input and a variable containing dark value
    """
    for entry in dic:
        if type(dic[entry]) is dict:
            dic[entry] = dark_subtract(dic[entry])
        else:
            dic[entry] - 100

    return dic
    print dic

我调用函数的方式如下:

dark_dic = dark_subtract(dic, d_value)
print "This is the original values:\n", dic
print "This is the dark current corrected values:\n", dark_dic

当打印字典 dic 时看起来像:

{'Band_1': array([[26176, 25920, 26816, ..., 53632, 53440, 52544],
       [25408, 24448, 23872, ..., 46592, 47040, 49216],
       [27264, 25024, 25792, ..., 50368, 51648, 51648],
       ..., 
       [32960, 32576, 32512, ..., 13568, 14528, 14720],
       [38784, 36416, 35648, ..., 18816, 15680, 16512],
       [33152, 32512, 32192, ..., 14464, 14720, 14784]], dtype=uint16)}

dark_val 只是一个整数(当前设置为 75)

有什么想法吗?

【问题讨论】:

    标签: python arrays numpy dictionary


    【解决方案1】:

    你已经有一个 NumPy 数组。因此,您可以直接减去整数:

     for key, value in dic.items():
          dic[key] = value - dark_val
    

    【讨论】: