在嵌套列表中查找具有最大数量的最高数字的列表

Find list in nested list with maximum number of highest numbers

我正在尝试在嵌套列表中查找具有最大数量的最高数字的列表,如下所示:

test_list = [[200,1,100],[50,120,0],[40,300,0]]
desired output = [200,1,100]

[200,1,100] 是这里的赢家,因为在它的 3 个数字中,有 2 个比其他列出的 2 个数字高。但是,这对顺序不敏感,例如:

test_list = [[1,100,200],[1,200,100],[200,1,100],[50,120,0],[40,300,0]]
desired output =  [[1,100,200],[1,200,100],[200,1,100]]

原因是这里所有三个构成了“最大”数字阵容。除了创建所有排列并比较它们之外还有其他方法吗?

编辑:为了进一步说明,对于上面的示例,嵌套列表中的数字为 300>200>120>100>50>40>1。那么,嵌套列表中哪个列表的最高数最多? [200,1,100]。嵌套列表中是否存在另一个列表,具有更多的最高数字?不,如果 [300,200,1] 在嵌套列表中,它就会获胜。

为了提供上下文,这些是一系列字符串之间模糊匹配的分数,以找到最接近的匹配项,每个字符串在列表中提供 3 个分数,在所有可能匹配项的列表中列出。这是我最接近字符串匹配的方式,比较模糊分数并从列表中取出可能得分最高的列表。

通过定义找到最大值:

  • 定义比较函数
  • 使用比较函数作为max中的key

代码

from functools import cmp_to_key 

def compare(sublist1, sublist2):
    '''
        Comparator function
        
        With >, <, = defined to satisfy the 
        requirements for comparing sublists 
        the function:
        
        Returns:
            Positive when sublist1 > sublist2
            Negative when sublist1 < sublist2
            0        when sublsit1 == sublist2
    '''
    return sum(1 if x > y else -1 for x, y in zip(sorted(sublist1), sorted(sublist2)) if x != y)


def find_max(lst):
    # find max value in list (using custom compare function)
    # use cmp_to_key to key to convert compare function to key
    m = max(lst, key=cmp_to_key(compare))
    
    # Use list comprehension to get all values equal 
    # max (equal when compare(m, x) == 0)
    return [x for x in lst if compare(m, x)==0]

测试

print(find_max([[200,1,100],[50,120,0],[40,300,0]])) 
# Output: [[200, 1, 100]]

print(find_max([[1,100,200],[1,200,100],[200,1,100],[50,120,0],[40,300,0]])) 
# Output [[1, 100, 200], [1, 200, 100], [200, 1, 100]]

print(find_max([[9, 9, 0], [1, 1, 1]])) 
# Output: [[9, 9, 0]]

print(find_max([[100, 100, 44, 100, 100, 56, 38], [100, 100, 100, 100, 100, 100, 73], [100, 100, 100, 100, 100, 100, 73], [100, 100, 100, 100, 100, 56, 41], [100, 100, 100, 100, 100, 56, 41], [100, 100, 100, 100, 100, 56, 41]] ))
# Output: [[100, 100, 100, 100, 100, 100, 73], [100, 100, 100, 100, 100, 100, 73]]