繁体   English   中英

从字典中2d数组中的每个元素中减去一个值

[英]Subtracting a value from each element in a 2d array within a dictionary

我试图从字典中的2D数组中的所有值中减去一个值( 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)

有任何想法吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM