Skip to main content
 首页 » 编程设计

Python:如何为字典分配一个长度不同的列表的值

2025年05月04日14cmt

我正在尝试在一系列 100 个二维 numpy 中定位质心像这样的数组:

array([[ 0.216,  0.24 ,  0.244, ...,  0.679,  0.684,  0.707], 
       [ 0.23 ,  0.229,  0.238, ...,  0.675,  0.676,  0.695], 
       [ 0.221,  0.238,  0.24 , ...,  0.669,  0.677,  0.684], 
       ...,  
       [ 0.937,  0.925,  0.923, ...,  0.768,  0.754,  0.752], 
       [ 0.937,  0.929,  0.923, ...,  0.737,  0.735,  0.741], 
       [ 0.934,  0.932,  0.929, ...,  0.72 ,  0.717,  0.728]]) 

基于这样的一组阈值 cutoff_values=[0.05,0.1,0.2] ,我为每个矩阵确定满足 cell_value>=0.05 的单元格区域, cell_value>=0.1和 cell_value>=0.2 .然后,我计算每个区域(或细胞组)的质心。

这将被执行 100 次。对于每个阈值,都有一个对应的 dictionary我在哪里存储质心坐标以列表的形式:

dict005={'matrix 1':[row for center of mass, column for center of mass]}对于阈值=0.05

dict01={...}对于阈值=0.1

dict02={...}对于阈值=0.2

但是,由于每个图像可能有多个区域或单元格组,其中 cell_value>=0.05 (例如)我最终会得到包含两倍于质心元素的列表(每个质心产生两个值——它的行和列)。

我的问题:我的 block (见下文)需要更改哪些内容才能正确填写 dicts我刚刚定义? 基本上,我问的是如何为字典分配一个值,该值是一个长度可变的列表。

示例: 截止值=0.05

dict005={'matrix 1':[17,29],'matrix 2':[23,45,88,101,234,432], 'matrix 3':[0,34,67,86]}

对于值>0.05,矩阵 1 有 1 个质心,矩阵 2 有 3 个,矩阵 3 有 2 个,依此类推,直到达到矩阵 100。

我的街区:

dict005 = OrderedDict() 
dict01 = OrderedDict() 
dict02 = OrderedDict() 
 
cutoff_values=[0.05, 0.1, 0.2] #A list containing all used cut-off values.  
 
for i, file in enumerate(os.listdir(directoryPath)): 
    if file.endswith(".csv"): 
 
       #The csv_to_matrix is computed here (my matrix of values) 
        for val in enumerate(cutoff_values): 
 
            if val == 0.05: 
                # Relabels the matrix True or False based on the >= condition, val=0.05 being the first cut-off 
                blobs = csv_to_matrix >= val  
                # Creates a few labels and records how many of them there are (nlabels) 
                labels, nlabels = ndimage.label(blobs) 
                # Empty list to store the coordinates row,column of the center of mass of each region 
                list005 = [] 
 
                # loop through the nlabels identified 
                for i in range(0, nlabels+1): 
                    # compute row, column index 
                    r, c = numpy.vstack(ndimage.center_of_mass(csv_to_matrix, numpy.arange(nlabels) + 1)).T 
                    # add row index as first element of the pair 
                    list005[i].append(r) 
                    # add column index as second element of the pair 
                    list005[i+1].append(c) 
                dict005[file] = list005  
 
            elif val == 0.1: 
                # Relabels the matrix True or False based on the >= condition, val=0.1 being the second cut-off 
                blobs = csv_to_matrix >= val 
                # Creates a few labels and records how many of them there are (nlabels) 
                labels, nlabels = ndimage.label(blobs) 
                # Empty list to store the coordinates row,column of the center of mass of each region 
                list01 = [] 
 
                # loop through the nlabels identified 
                for i in range(0, nlabels+1): 
                    # compute row, column index 
                    r, c = numpy.vstack(ndimage.center_of_mass(csv_to_matrix, numpy.arange(nlabels) + 1)).T 
                    # add row index as first element of the pair 
                    list01[i].append(r) 
                    # add column index as second element of the pair 
                    list01[i+1].append(c) 
                dict01[file] = list01 
 
            elif val == 0.2: 
                # Relabels the matrix True or False based on the >= condition, val=0.2 being the third cut-off 
                blobs = csv_to_matrix >= val 
                # Creates a few labels and records how many of them there are (nlabels) 
                labels, nlabels = ndimage.label(blobs) 
                # Empty list to store the coordinates row,column of the center of mass of each region 
                list02 = [] 
                # loop through the nlabels identified 
                for i in range(0, nlabels+1): 
                    # compute row, column index 
                    r, c = numpy.vstack(ndimage.center_of_mass(csv_to_matrix, labels, numpy.arange(nlabels) + 1)).T 
                    # add row index as first element of the pair 
                    list02[i].append(r) 
                    # add column index as second element of the pair 
                    list02[i+1].append(c) 
                dict02[file] = list02 

请您参考如下方法:

不是每次都创建一个新列表,而是检索任何现有列表并附加到它。

一个简单的方法是使用 defaultdict 而不是 OrderedDict

from collections import defaultdict 
d = defaultdict(list) 
d['somefile.csv'].extend([3, 4]) 
print(d) 
# defaultdict(<type 'list'>, {'somefile.csv': [3, 4]}) 
d['somefile.csv'] 
# [3, 4]