简体   繁体   English

在 Python 中查找多个元素的最小值和最大值

[英]Find min and max value of multiple element in Python

I'm newbie both in the forum and in Python, I hope I'll do everything in the right way (tell me everything I'm doing wrong so I can improve it).我是论坛和 Python 的新手,我希望我能以正确的方式做所有事情(告诉我我做错的所有事情,以便我改进它)。

About my question : I've many class-object (is this the correct name?) in a list (this class-object are all the rectangle inside a matrix(=nested list)).关于我的问题:我在一个列表中有很多类对象(这是正确的名称吗?)(这个类对象都是矩阵内的矩形(=嵌套列表))。

All of this rectangle has many attributes, some of these are: " X_SX ", " Y_SX ", " X_DX ", " Y_DX " (they are the coordinates of left-up vertex ("X_SX", "Y_SX") and right-down vertex ("X_DX", "Y_DX") of the rectangle.所有这个矩形都有很多属性,其中一些是:“ X_SX ”、“ Y_SX ”、“ X_DX ”、“ Y_DX ”(它们是左上顶点的坐标(“X_SX”、“Y_SX”)和右-矩形的下顶点(“X_DX”,“Y_DX”)。

I've to find the min value of X_SX and Y_SX and the max value of X_DX and Y_SX .我必须找到 X_SX 和 Y_SX 的最小值以及 X_DX 和 Y_SX最大值 This is what I've done:这就是我所做的:

def find_box(rectangles):
    x_sx = (min(getattr(rec, 'x_sx') for rec in rectangles))
    y_sx = (min(getattr(rec, 'y_sx') for rec in rectangles))
    x_dx = (max(getattr(rec, 'x_dx') for rec in rectangles))
    y_dx = (max(getattr(rec, 'y_dx') for rec in rectangles))

It actually work but I was wondering if there is a way to do it in a better way and avoid to call the for-loop 4 times in the same list它确实有效,但我想知道是否有办法以更好的方式做到这一点,并避免在同一个列表中调用 for 循环 4 次

NOTE: I'm not sure if I explain this badly but for a better comprehension this is the list "rectangles" where "Rectangle" is the Class I've definied:注意:我不确定我是否解释得不好,但为了更好地理解,这是列表“矩形”,其中“矩形”是我定义的 Class:

[<__main__.Rettangolo object at 0x000001FAF3971C70>, <__main__.Rettangolo object at 0x000001FAF36E2B80>, <__main__.Rettangolo object at 0x000001FAF3971850>, <__main__.Rettangolo object at 0x000001FAF3B55A30>]

Thank you for your time and your help!感谢您的时间和帮助!

I agree with Turun Ambartanen that your code is readable as is.我同意 Turun Ambartanen 的观点,即您的代码按原样可读。 Should you desire to speed things up, I will point you to the numpy python standard library (numpy is "numerical python.")如果您想加快速度,我将向您指出 numpy python 标准库(numpy 是“数字 python”。)

Numpy arrays will allow you to eliminate iterations, if that's desirable.如果需要,Numpy arrays 将允许您消除迭代。 If you have a lot of rectangles in your list, you will get a big performance boost by using them.如果您的列表中有很多矩形,那么使用它们会大大提高性能。 (I think I see just four in your example, so this might go beyond what you're looking for.) The disadvantage of arrays is that they may result in harder to read code. (我想我在你的例子中只看到了四个,所以这可能超出了你正在寻找的 go。) arrays 的缺点是它们可能会导致更难阅读代码。 I may be going beyond what a person new to python is trying to learn, but here goes:我可能会超出 python 的新手想要学习的内容,但这里有:

## import numpy and give it the short name 'np'
import numpy as np

## Define a numpy array from the lists.
## np.array takes lists and turns them into the axes of
## an array.

corners = np.array([[rec.x_sx,
                     rec.x_sy, 
                     rec.x_dx, 
                     rec.x_dy] for rec in rectangles])

## Numpy provides functions for doing math along the rows
## and columns of an array. (And lots more!)
## np.max returns the largest element in an array
## the axis argument says which dimension to find the max
## on. This produces a 1 row, 4 column array

maxima = np.max(corners, axis = 0)

## And for the min-values
minima = np.min(corners, axis = 0)

##Edit: finally, so the values are stored as you did above:
x_sx = maxima[0]
y_sx = maxima[1]
x_dx = minima[2]
y_dx = minima[3]

You can index numpy arrays in ways similar to lists (except they can be multi-dimensional.) The above code gives a 1D array, so you can get the x_sx value you want with maxima[0]您可以以类似于列表的方式索引 numpy arrays(除了它们可以是多维的。)上面的代码给出了一个一维数组,因此您可以使用maxima[0]获得所需的 x_sx 值

Aside from using rec.x_sx instead of getattr() this seems like a very readable solution to me.除了使用rec.x_sx而不是getattr()之外,这对我来说似乎是一个非常易读的解决方案。

If you definitely want to get rid of the four list comprehensions you could make one big loop in which you track the least/greatest value of the desired property (x_sx, ...) and the rectangle to which it belongs.如果您确实想摆脱四个列表推导,您可以创建一个大循环,在其中跟踪所需属性(x_sx,...)及其所属矩形的最小/最大值。

min_x_sx = 1000  # a very big number. 
                 # tracking max values in a list requires starting with a very small number
min_x_sx_rectangle = None
# for the other three corners as well
for rec in rectangles:
    if rec.x_sx < min_x_sx:
        min_x_sx_rectangle = rec
        min_x_sx = rec.x_sx
    # for the other three corners as well

min and max take a key function, so minmax取一个密钥 function,所以

x_sx = (min(getattr(rec, 'x_sx') for rec in rectangles))

can be written as:可以写成:

from operator import attrgetter
x_sx = min(rectangles, key=attrgetter('x_sx')).x_sx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM