Python:比较两个以上数组之间的值

时间:2013-12-26 18:16:36

标签: python arrays max

我必须比较3个或更多如下所示的数组:

{'Class1': {'diag': {'Class1': array([-138.49760438, -133.93161498, ...]),
                     'Class2': array([-20.78214408, -19.33358523, ...])
                     'Class3': array([-338.81699294, -345.05932059, ...])}
           }
}

我想比较每个数组中的前3个值,搜索最大数字并将相应的类(1,2或3)输出到新数组中。然后转到第二个3值并执行相同操作。每个数组包含大约100,000个值,因此该过程应该相当快。

在上面的例子中,我应该得到以下数组:['Class2','Class2']。

我只找到了可以使用2个数组但不能更多的函数。事实上,我需要它来处理任意数量的数组,因为在我的实验过程中类会增加。

我期待听到您的想法!

2 个答案:

答案 0 :(得分:2)

from itertools import izip
from operator import itemgetter

# Ignoring the outer levels of the dict and shortening the numbers.
data = {
    'Class1' : [-138, -133,  33, 999],
    'Class2' : [ -20,  -19, 100, 777],
    'Class3' : [-338, -345, 200, 111],
}

lookup    = dict(enumerate(data.keys()))
max_index = lambda ns: max(enumerate(ns), key = itemgetter(1))[0]

# Zip the arrays together.
# For each zipped-set of numbers, find the index of the max.
# Use that index to look up the class name.
classes = [lookup[max_index(ns)] for ns in izip(*data.values())]

print classes    # ['Class2', 'Class2', 'Class3', 'Class1']

答案 1 :(得分:1)

假设您的数组具有相同的长度,则从0迭代到len(array1)。在每次迭代中,我都会从所有数组的第i个元素构建一个列表。然后,您可以使用以下内容在结果列表中找到最大元素及其索引:

import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

索引对应于您的最大值来自的类别,例如0 - > class1,1 ---> class2等等。因此,解决方案的时间复杂度应该是数组长度的线性(以及类的数量,具体取决于max的实现)。