我有一个关于如何在python字典中使用键的问题。
我有一个检测器设置,我用一个嵌套的字典来表示它。探测器由3个子阵列组成,每个子阵列由5行组成,每行包含48个像素。每个像素都有一个x-y坐标和强度。因此,我将这个结构表示为:
def pixel_grid(self):
# create a tree-like structure to access every pixel :
# every pixel has the following components
pixel = {'coord_x' : [], 'coord_y' : [], 'intensity' : None}
# create an index to access each pixel 'p1'-'p48'
pix_ind = ['p'+str(i) for i in range(1,49)]
# create a row index : 'row1'-'row5'
pix_arrays = ['row'+str(i) for i in range(1,6)]
# create a sub-array, which consist of 5 rows with 48 pixels per row
sub = { name:{ key: pixel for key in pix_ind} for name in pix_arrays}
# create a detector with 3 sub-arrays
self.detector = {'sub1' : sub,
'sub2' : sub,
'sub3' : sub}
# assign coordinates to each pixel:
# begin with a middle sub-array, middle row, middle pixel
pix_width = 1.294
begin_x = 0
end_x = pix_width
self.detector['sub2']['row3']['p25']['coord_x'] = [begin_x, end_x]
'''
The following loop would be used to assign coords to other pixels,
but currently is used to check the x-coord of the pixels
'''
for i, p in enumerate(self.detector['sub2']['row3'].keys()):
print(p, ':', self.detector['sub2']['row3'][p]['coord_x'])
return None
然而,当我打印x_coord
时,像素p25
的坐标似乎被分配给了每个像素!这是打印的结果:
p1 : [0, 1.294]
p2 : [0, 1.294]
p3 : [0, 1.294]
p4 : [0, 1.294]
...
...
p45 : [0, 1.294]
p46 : [0, 1.294]
p47 : [0, 1.294]
p48 : [0, 1.294]
我不明白为什么会这样。我期望除了p25
之外的所有像素都有一个空的coord_x
列表,它实际上是[0, 1.294]
。我做错了什么?如何获得这样的输出:
p1 : []
p2 : []
...
...
p24 : []
p25 : [0, 1.294]
p26 : []
...
...
p48 : []
谢谢你的帮助!
您指的是相同的列表。
尝试:
from copy import deepcopy
sub = { name:{ key: deepcopy(pixel) for key in pix_ind} for name in pix_arrays}
self.detector = {'sub1' : deepcopy(sub),
'sub2' : deepcopy(sub),
'sub3' : deepcopy(sub)}