Python 3.x 如何在Python中的字典中创建双循环?
我有一个数据立方体,有二维坐标和三维波长。我的目标是为给定半径的圆外坐标到中心坐标(代码中的x0和y0)编写一个掩码。为此,我尝试使用字典,但我使用throuble,因为我似乎必须在字典中做一个双循环来迭代二维,作为字典的初学者,我还不知道如何做到这一点 我编写了以下代码Python 3.x 如何在Python中的字典中创建双循环?,python-3.x,Python 3.x,我有一个数据立方体,有二维坐标和三维波长。我的目标是为给定半径的圆外坐标到中心坐标(代码中的x0和y0)编写一个掩码。为此,我尝试使用字典,但我使用throuble,因为我似乎必须在字典中做一个双循环来迭代二维,作为字典的初学者,我还不知道如何做到这一点 我编写了以下代码 x0 = 38 y0 = 45 radius = 9 xcoords = np.arange(1,flux.shape[1]+1,1) ycoords = np.arange(1,flux.shape[2]+1,1) ma
x0 = 38
y0 = 45
radius = 9
xcoords = np.arange(1,flux.shape[1]+1,1)
ycoords = np.arange(1,flux.shape[2]+1,1)
mask = {'xmask': [xcoords[np.sqrt((xcoords[:]-x0)**2 + (y-y0)**2) < radius] for y in ycoords], 'ymask': [ycoords[np.sqrt((x-x0)**2 + (ycoords[:]-y0)**2) < radius] for x in xcoords]}
x0=38
y0=45
半径=9
xcoords=np.arange(1,通量形状[1]+1,1)
ycoords=np.arange(1,通量形状[2]+1,1)
掩码={'xmask':[xcoords[np.sqrt((xcoords[:]-x0)**2+(y-y0)**2)
它返回了几个数组,y的每个值一个(对于xmask),x的每个值一个(对于ymask),尽管我只需要每个数组一个。谁能说出我做错了什么,以及如何实现我的目标
注意:我也没有使用字典,因为
xmask = []
for x in xcoords:
for y in ycoords:
if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
xmask.append(x)
break
ymask = []
for y in xcoords:
for x in ycoords:
if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
ymask.append(y)
break
xmask=[]
对于xcoords中的x:
对于ycoords中的y:
如果np.sqrt((x-x0)**2+(y-y0)**2)<半径:
xmask.append(x)
打破
ymask=[]
对于xcoords中的y:
对于ycoords中的x:
如果np.sqrt((x-x0)**2+(y-y0)**2)<半径:
ymask.append(y)
打破
但我希望有可能提高效率
谢谢你的帮助
编辑:我意识到不需要循环。如果我选择y=y0和x=x0,我分别得到圆内的x和y的值。所以我留下来了
mask = {'xmask': [xcoords[abs(xcoords[:]-x0) < radius]], 'ymask': [ycoords[abs(ycoords[:]-y0) < radius]]}
mask={'xmask':[xcoords[abs(xcoords[:]-x0)
OP解释分配
mask = {'xmask': [xcoords[abs(xcoords[:] - x0) < radius]],
'ymask': [ycoords[abs(ycoords[:] - y0) < radius]]}
mask={'xmask':[xcoords[abs(xcoords[:]-x0)
解决了问题。OP解释分配
mask = {'xmask': [xcoords[abs(xcoords[:] - x0) < radius]],
'ymask': [ycoords[abs(ycoords[:] - y0) < radius]]}
mask={'xmask':[xcoords[abs(xcoords[:]-x0)
解决了问题。您的理解有循环。您忘记了列表理解(dict中的值)周围的方括号[]。Ups,谢谢。现在我才意识到我不需要任何循环。只需一个
mask={'xmask':[xcoords[np.sqrt((xcoords[:]-x0)**2)
我就可以得到我的mask了。你的理解有循环。你忘记了列表理解(口述中的值)周围的方括号[]。谢谢。现在我才意识到我不需要任何循环。只要一个mask={'xmask':[xcoords[np.sqrt((xcoords[:]-x0)**2)
我就得到了我的mask。