在Python中填充for循环中的dict

时间:2014-02-04 17:24:56

标签: python python-2.7 for-loop dictionary directory

我有一个文件夹,包含子文件夹(SEQ1,SEQ2,SEQ3等),每个子文件夹包含40张图像。

我想遍历每个图像,执行产生值的操作,然后获取每个子文件夹中40个值的平均值,并将此值放在dict中作为带有子标题的'value' - 文件夹是'关键'。

以下是我的尝试:

dic = {}

for (dirname, dirnames, filenames) in   os.walk('C:\Users\....'):

for keys in dirnames:
rec_3 = []


    for subdirname in filenames:

        ds = dicom.read_file(os.path.join(dirname, subdirname)) #reading in DICOM images
        lx, ly = ds.pixel_array.shape  # beginning of operation
        X, Y = np.ogrid[0:lx, 0:ly]
        mask = (X - lx/2)**2 + (Y - ly/2)**2 < lx*ly/8
        st_dev = np.std(ds.pixel_array[mask]) # end of operation
        rec_3.append(st_dev)
    rec_3_avg = np.mean(rec_3)
    dic.update({keys:rec_3_avg})

print dic  

我得到以下结果“{'SEQ3':nan,'SEQ2':nan,'SEQ1':nan,'SEQ4':nan}”

我的理想结果是每个子文件夹中平均有40个值作为此处的值,而不是“nan”。

非常感谢。

2 个答案:

答案 0 :(得分:0)

你能试试这个版本吗?

dic = {}

for root, dirs, files in os.walk('C:\Users\....'):
    for dirname in dirs:
        if dirname.startswith('.'):
          dirs.remove(dirname)
    rec_3 = []        
    for filename in files:    
        ds = dicom.read_file(os.path.join(root, filename)) #reading in DICOM images
        lx, ly = ds.pixel_array.shape  # beginning of operation
        X, Y = np.ogrid[0:lx, 0:ly]
        mask = (X - lx/2)**2 + (Y - ly/2)**2 < lx*ly/8
        array = ds.pixel_array[mask]
        if array.all():
            st_dev = np.std(array) # end of operation
            rec_3.append(st_dev)
    rec_3_avg = np.mean(rec_3)
    dic.update({os.path.basename(root):rec_3_avg})

print dic

答案 1 :(得分:0)

我会首先在子目录中创建这些值的字典,然后计算其后的方法,只是个人偏好,更容易阅读。

dic_std_dev = {}
base_path = '.'
for root, dirs, files in os.walk(base_path):
    #print dirs
    for f in files:
        if root != base_path: #If this is a subdirectory
            ds = dicom.read_file(os.path.join(root, f)) #reading in DICOM images
            lx, ly = ds.pixel_array.shape  # beginning of operation
            X, Y = np.ogrid[0:lx, 0:ly]
            mask = (X - lx/2)**2 + (Y - ly/2)**2 < lx*ly/8
            array = ds.pixel_array[mask]
            if array:
                st_dev = np.std(array) # end of operation
                if root in dic_std_dev.keys():
                    dic_std_dev[root].append(st_dev)
                else:
                    dic_std_dev[root] = [st_dev]

dic = {}
for key in dic_std_dev.keys():
    if len(dic_std_dev[key]) > 0:
        dic[key] = np.mean(dic_std_dev[key])

print dic