有什么方法可以在听写理解中听写理解吗?
Any way to dict comprehension in dict comprehension in dict comprehension this?
我有这段代码:
position = {}
for x in range(imdim[0]-shapesize+1):
for y in range(imdim[1]-shapesize+1):
curim = im[x:x+shapesize,y:y+shapesize]
shapedict = {}
for shapeid,(shape,contour) in enumerate(zip(shapes,contours)):
values = {}
curshape = curim[shape]
curcontour = curim[contour]
values['meandiff'] = curshape.mean()-curcontour.mean()
values['maxmin'] = int(curshape.min())-int(curcontour.max())
shapedict[shapeid] = values
position[(x,y)] = shapedict
return position
...其中 im 是一个图像(numpy 数组),imdim 它的形状、形状和轮廓是比 im 更小维度(shapesize*shapesize)的二进制数组的列表。
它确实有效,但我想知道是否有一种方法可以用字典理解、初始风格来编写所有这些内容。如果是,它会 运行 更快吗?
此外,欢迎对样式或优化发表任何评论!
我觉得应该可以,但我没有真正测试过:
position = {
(x, y): {
shapeid: {'meandiff': curim[shape].mean() - curim[contour].mean(),
'maxmin': int(curim[shape].min()) - int(curim[contour].max())}
for shapeid,(shape,contour) in enumerate(zip(shapes,contours))
}
for (x,y,curim) in ((x, y, im[x:x+shapesize, y:y+shapesize])
for x in range(imdim[0]-shapesize+1)
for y in range(imdim[1]-shapesize+1)
)
}
棘手的部分是您定义的临时变量。对于 curim
我创建了一个内部生成器表达式,否则你必须写四次该表达式。您可以对 curshape
和 curcontour
执行相同的操作,但我认为不值得增加嵌套级别。
是否更快:可能不会,当然不会很明显。恕我直言,更重要的是代码的可读性。这当然是见仁见智了。就个人而言,我认为它比您的原始代码更具可读性。
我有这段代码:
position = {}
for x in range(imdim[0]-shapesize+1):
for y in range(imdim[1]-shapesize+1):
curim = im[x:x+shapesize,y:y+shapesize]
shapedict = {}
for shapeid,(shape,contour) in enumerate(zip(shapes,contours)):
values = {}
curshape = curim[shape]
curcontour = curim[contour]
values['meandiff'] = curshape.mean()-curcontour.mean()
values['maxmin'] = int(curshape.min())-int(curcontour.max())
shapedict[shapeid] = values
position[(x,y)] = shapedict
return position
...其中 im 是一个图像(numpy 数组),imdim 它的形状、形状和轮廓是比 im 更小维度(shapesize*shapesize)的二进制数组的列表。
它确实有效,但我想知道是否有一种方法可以用字典理解、初始风格来编写所有这些内容。如果是,它会 运行 更快吗?
此外,欢迎对样式或优化发表任何评论!
我觉得应该可以,但我没有真正测试过:
position = {
(x, y): {
shapeid: {'meandiff': curim[shape].mean() - curim[contour].mean(),
'maxmin': int(curim[shape].min()) - int(curim[contour].max())}
for shapeid,(shape,contour) in enumerate(zip(shapes,contours))
}
for (x,y,curim) in ((x, y, im[x:x+shapesize, y:y+shapesize])
for x in range(imdim[0]-shapesize+1)
for y in range(imdim[1]-shapesize+1)
)
}
棘手的部分是您定义的临时变量。对于 curim
我创建了一个内部生成器表达式,否则你必须写四次该表达式。您可以对 curshape
和 curcontour
执行相同的操作,但我认为不值得增加嵌套级别。
是否更快:可能不会,当然不会很明显。恕我直言,更重要的是代码的可读性。这当然是见仁见智了。就个人而言,我认为它比您的原始代码更具可读性。