首页 > 解决方案 > 两个列表计算特定元素并根据特定规则聚合

问题描述

嗨,我偶然发现了一些我无法解决的问题。 我有两个列表 list1=[2,5,7]list2=[4,6,9]和以及以下变量

counter1=[], counter2=[] # Counter of each list,
sum1=[], sum2=[] # Sum of highest elements

在这种情况下,我想从列表中选择前三个最高元素9, 7, 6 (9,7 from list1 and 6 from list2)。因此,我需要将每个数字所属的列表(例如 9,7)映射到 list1,因此我需要增加计数器变量以计算每个列表中的前 3 个元素中有多少包含在我们的玩具示例counter1=[2 ]counter2=[1]

此外,我还需要增加 sum1 以从每个列表中获取每个top3的总和,例如 sum1=[9+6=15]sum2=[7]

您想帮助弄清楚如何解决这一挑战吗?欢迎提出任何解决问题的方法。最后但并非最不重要的一点是,可以建议我们如何为不同的场景构建,例如代替top3元素让我们说top5以及我们如何将其包装到函数中。

注意我不能在两个列表中有相同的数字。

标签: pythonlist

解决方案


有许多可能的解决方案。在我看来,这是最简单的:

import heapq

list1 = [2,5,7]
list2=[4,6,9]

counter1=0
counter2=0

sum1=0
sum2=0

full_list = list1 + list2
three_largest = heapq.nlargest(3,full_list)

for n in three_largest:
    if n in list1:
        list1.remove(n)
        counter1+=1
        sum1+=n
    else:
        list2.remove(n)
        counter2+=1
        sum2+=n

print(counter1)
print(counter2)
print(sum1)
print(sum2)

请注意,您在示例中为您提供的值犯了一个错误。9 在列表 2 中

编辑

这是一个处理M个列表中N个最高数字的示例:

import heapq
from typing import List

list_of_lists = [[1,2,3,4],[4,3,7,12],[8,8,10,1]]



def quick_metric(n_highest,lists:List[List[int]]):
    counters = [0 for i in range(len(lists))]
    sums = [0 for i in range(len(lists))]
    flat_list = [item for sublist in lists for item in sublist]
    highest = heapq.nlargest(n_highest, flat_list)

    for n in highest:
        for x_list in lists:
            if n in x_list:
                x_list.remove(n)
                counters[lists.index(x_list)]+=1
                sums[lists.index(x_list)]+=n
                break

    print(counters)
    print(sums)
    print(highest)


quick_metric(3,list_of_lists)

输出:

[0, 1, 2]
[0, 12, 18]
[12, 10, 8]

推荐阅读