python - 两个列表计算特定元素并根据特定规则聚合
问题描述
嗨,我偶然发现了一些我无法解决的问题。
我有两个列表 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以及我们如何将其包装到函数中。
注意我不能在两个列表中有相同的数字。
解决方案
有许多可能的解决方案。在我看来,这是最简单的:
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]
推荐阅读
- javascript - jsTree:是否可以将 JSON 映射提供给树(而不是 JSON 数组)?
- lua - Lua if 返回 false 但应该返回 true
- python - 使用 Quart 的扩展 Quart-OpenAPI 进行 pytest 测试的完整示例在哪里?
- date - 如果满足条件,SharePoint 嵌套 If 语句可将日期添加到日期
- c - 如何确定 Int 是否为 16 位
- heroku - Heroku - 从终端管理不同的应用程序
- laravel-5.7 - “ReflectionException:类配置不存在”更新到 Laravel 5.7
- python - 有没有更优雅的方法来通过二维数组中的索引取值?
- javascript - 旋转方法使一切旋转
- typescript - 为什么详尽检查对联合类型的工作方式不同?