简体   繁体   English

在两个列表中找到k个最小的对

[英]Find k smallest pairs in two lists

My goal is to: 我的目标是:

  1. pair the elements in two lists; 将两个列表中的元素配对; and
  2. find the k smallest pairs. 找到k最小的对。

At the moment I can pair every element in both lists with the code below: 目前,我可以将两个列表中的每个元素与以下代码配对:

import itertools  

a = [1, 3, 5, 7]
b = [2, 4, 6, 8]
c = list(itertools.product(a, b))

print c

And my output is: 我的输出是:

[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8)]

Suppose I set k = 3 , it should return me the three smallest pairs: (1, 2) , (1, 4) and (3, 2) . 假设我设置k = 3 ,它应该返回给我三个最小的对: (1, 2)(1, 4)(3, 2) How do I do that? 我怎么做?

You can use heapq.nsmallest with sum as its key function : 您可以使用带有sum heapq.nsmallest作为其关键功能:

>>> import heapq
>>> heapq.nsmallest(3,c,key=sum)
[(1, 2), (1, 4), (3, 2)]

Or as @jonrsharpe said in comment you can use sorted : 或者如@jonrsharpe在评论中所说,您可以使用sorted

sorted(c, key=sum)[:k]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM