根据对象属性的最大值合并对象列表的最有效方法



我想做与本文完全相同的事情,但使用对象的2d数组,而不仅仅是数字的2d数组。

class ExchangeRate:
rate = None
name = None
otherUsefulProperty = None
def __init__(self, _rate, _name, _otherUsefulProperty):
self.rate = _rate
self.name = _name
self.otherUsefulProperty = _otherUsefulProperty

这是我对象的类。rate属性将是在将图合并在一起时使用的属性。

下面的代码适用于二维数字数组,但我还没能想出如何有效地处理二维对象数组。请注意,性能对我所做的工作至关重要。这是假设一个二维数组的对象确实是有性能的。如果不是,还有更具表演性的方式,请告诉我。

import numpy as np
graph = np.ndarray(shape=(4, 3, 3), dtype=float, order='F')
graph[0] = [[0, 0, 1], [1, 0, 1], [2, 0, 0]]
graph[1] = [[0, 0, 1], [1, 0, 1], [2, 0, 0]]
graph[2] = [[5, 0, 0], [1, 0, 1], [2, 0, 0]]
graph[3] = [[2, 1, 0], [9, 0, 1], [0, 0, 0]]
PrintAndLog("graph of type " + str(type(graph)) + " = n" + str(graph))
PrintAndLog("nn")
resultGraph = graph.max(axis=0)
PrintAndLog("resultGraph of type " + str(type(resultGraph)) + " = n" + str(resultGraph))

输出:

graph of type <class 'numpy.ndarray'> = 
[[[ 0.  0.  1.]
[ 1.  0.  1.]
[ 2.  0.  0.]]
[[ 0.  0.  1.]
[ 1.  0.  1.]
[ 2.  0.  0.]]
[[ 5.  0.  0.]
[ 1.  0.  1.]
[ 2.  0.  0.]]
[[ 2.  1.  0.]
[ 9.  0.  1.]
[ 0.  0.  0.]]]

resultGraph of type <class 'numpy.ndarray'> = 
[[ 5.  1.  1.]
[ 9.  0.  1.]
[ 2.  0.  0.]]

可能的最终解决方案:

希望其他人觉得这很有用。我刚刚做了大量的性能测试,显然是赢家。

TLDR:获胜者=np.array+ExchangeRate object+graph.max(axis=0)。这是迄今为止我尝试过的最快的方法。同样,目标是合并许多费率图,其中每个费率也有与其相关的元数据,需要与一起合并

以下是我将其缩小到的最终方法的测试结果。每个测试都是基于合并来计时的(我根据速率将几个图合并为一个图(。我记录了以下数据点:超过200次跑步的平均持续时间,以及第一次跑步的持续时间。第一次跑步很重要,因为它有时似乎比平均时间长。这可能与缓存有关。

  • test_graph_4 200次平均运行=0.0003026秒(首次运行,相同(

  • test_graph_3 200次运行平均值=0.0003836秒(第一次运行,~相同(

  • test_graph2b 200次平均运行时间=0.000018秒(首次运行0.000092秒(

  • test_graph2a 200次跑步平均值=0.000066秒(第一次跑步0.000143秒(

我认为您只需要实现__lt__方法:

class ExchangeRate:
rate = None
name = None
otherUsefulProperty = None
def __init__(self, _rate, _name, _otherUsefulProperty):
self.rate = _rate
self.name = _name
self.otherUsefulProperty = _otherUsefulProperty

# this method allows sorting, comparison, etc.
def __lt__(self, other):
return self.rate < other.rate
a = np.array([ExchangeRate(3,2,1)])
b = np.array([ExchangeRate(1,2,3)])
a>b

输出:

True

最新更新