优化列表的python列表上的最小操作 [英] Optimise a minimum operation on a python list of list
问题描述
我有一个列表列表,其中每个列表都对应于图形的边界点.我必须提取四个点的列表,每个点定义图形的封闭矩形.例如,我有这个列表
I have a list of list where each list corresponds to the boundary point of a figure. I have to extract a list of four points, each defining the enclosing rectangle of the figures. For example, I have this list
[[[2,5],[3,4],[5,8],[5,6],[5,9]],
[[11,14],[12,15],[16,17]],
...
]
此处每个列表都定义了图形边界.我要得到的是作为
Here each list defines a figure boundary. what I have to get is list of four points as
[[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]]
即
[[[2,4],[2,9],[5,9],[5,4]],
[[11,14], [11, 17], [16,17], [16,14]]
...
]
我已经使用python循环完成了此任务,该循环非常正常. 这是代码.
I have done this using python loop which is perfectly working. Here is the code.
cleaned_contours = list()
for cur_cont in contours:
min_x, min_y = cur_cont.min(axis=0).flatten()
max_x, max_y = cur_cont.max(axis=0).flatten()
cleaned_contours.append(np.array([[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]]))
有没有一种方法可以执行此操作而无需使用循环或列表理解. 我正在使用python3.
Is there a way I can do this without using loops or list comprehension. I am using python3.
推荐答案
如果愿意,您可以使用理解力(仍然是循环+丑陋的):
You can use comprehension if you like (still a loop + ugly):
a = [[[2,5],[3,4],[5,8],[5,6],[5,9]], [[11,14],[12,15],[16,17]]]
[[[j[0], j[1]], [j[0], j[3]], [j[2], j[3]], [j[2], j[1]]] for j in [np.array(i).min(0).tolist() + np.array(i).max(0).tolist() for i in a]]
#[[[2, 4], [2, 9], [5, 9], [5, 4]],
# [[11, 14], [11, 17], [16, 17], [16, 14]]]
这篇关于优化列表的python列表上的最小操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!