2010-10-09 85 views
1

我有以下数组:Python:我如何在子数组元素中找到最小值和最大值?

[[499, 3], [502, 3], [502, 353], [499, 353]] 

他们是一个长方形的verteces。

我需要找到左上角,右上角,左下角和右下角的顶点。

什么是最好的Python代码来做到这一点?

感谢

+0

@systempuntoout出了什么问题?不是一个数组? – aneuryzm 2010-10-09 21:48:41

+0

在Python中,您应该调用该数据结构a [list](http://docs.python.org/tutorial/datastructures.html);还有其他模块可以提供数组对象([array](http://docs.python.org/library/array.html)和[numpy](http://www.scipy.org/Tentative_NumPy_Tutorial)) – systempuntoout 2010-10-09 22:01:41

回答

2

编辑:感谢tokand的指出,这可以与元组拆包来完成。

您可以对其进行排序。

(bottomleft, bottomright,topleft, topright) = sorted(vertices) 

,或者你可以用

corners.sort() 
(bottomleft, bottomright,topleft, topright) = corners 
# the unpacking here is redundant but demonstrative 

仅供参考做到位,有序输出为:

>>> a = [[499, 3], [502, 3], [502, 353], [499, 353]] 
>>> sorted(a) 
[[499, 3], [499, 353], [502, 3], [502, 353]] 
>>> 

这将是O(nlogn),而有一定Ø (n)解决方案。但是对于这个大小的列表,除非你有很多这样的大小,否则我不认为它是一个biggy(在这种情况下,本地C实现的速度将超越自定义python函数,所以它仍然是实用的透视图。)

+1

想法与tuple解包:topleft,topright,bottomleft,bottomright =排序(顶点) – tokland 2010-10-09 21:40:33

+0

@tokland,好主意。我猜想我刚刚得到了这个观点。这可能是我真正写的。 – aaronasterling 2010-10-09 21:41:48

0
vertices = [[499, 3], [499, 353], [502, 3], [502, 353]] 

# if the origin is the top left 
(topleft, bottomleft, topright, bottomright) = sorted(vertices) 

# if the origin is the bottom left 
(bottomleft, topleft, bottomright, topright) = sorted(vertices) 
相关问题