从 Python 中的列表中查找 5 个最小的数字

Finding the 5 smallest numbers from a list in Python

我有一个名字列表 x 和一个分数列表 y,它们与名字相对应。

x = {a,b,c,d,e,f,g,h,i,j,k} 
y= {8,8,15,13,12,17,18,12,14,14} 

所以,a 得分 8,b 得分 8,c 得分 15,...,k 得分 14

我想从列表 y 中找到 5 个最小的分数,并得到他们的名字并打印出类似于以下内容:

top5 最低分:

a : 8
b : 8 
e : 12
h : 12 
d : 13

目前,我正在创建列表的副本,然后使用 pop 不断减少列表,但它给我的乐谱名称不正确。但是,当我为 max5 值创建列表时,使用相同的方法一切都很好。我不确定 python 中是否有允许我执行此操作的函数。这只是我的问题的一个示例,我真正的问题涉及商店位置以及我从函数计算出的那些商店的分数,但我想获得前 5 个最高分和 5 个最低分。有人对此有有效的解决方案吗?

Python 有一个名为 Dictionary 的数据结构,可用于存储 key/value 对。在 Python 中,字典定义为 -

dict = {'a':8 , 'b':8, 'c':15, 'd':13 ...}

然后你可以遍历这个字典中的键值对,找到5个最小的数字。

可以将dict转为tuple,然后根据第二项对tuple进行排序-

import operator
dict = {'a':8 , 'b':8, 'c':15, 'd':13 ...}
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))

除了使用字典,您还可以使用 list of tuples,并使用上面代码的最后一行根据每个元组的第二个元素对其进行排序。

元组列表看起来像 -

scores = [('a',8),('b',8),('c',15),('d',13)..]

首先,整理你的输入集合

假设你有输入 xy 其中每个分别是标签和分数的集合:

x = ['a','b','c','d','e','f','g'] 
y = [5,3,10,2,2,1,0]

要按相应的分数 yx 进行排序,将它们压缩在一起并按分数排序,取前 5 个即可:

min_list = sorted(zip(x,y), key=lambda t: t[1])[5:]

Quick explanation

It zips x and y together so you have a list of zip(x,y) = ('a',5), ('b',3), ...

Then you sort that list by the second element of each tuple sorted( zip(x,y )) where the key for sorting is the second element of tuple (t[1])

Lastly, take the first 5 elements of the sorted list [5:]

您生成的集合如下所示:

[('g', 0), ('f', 1), ('d', 2), ('e', 2), ('b', 3)]

首先,{8,8,15...} 会创建一个 set,而不是 list;由于套装没有排序,您不能像这样将 2 套组合在一起。

因此你有

x = ['a','b','c','d','e','f','g','h','i','j','k'] 
y = [8, 8, 15, 13, 12, 17, 18, 12, 14, 14]

现在,要将它们组成 letter, score 对,请使用 zip 函数。

pairs = zip(x, y)

然后您可以从 heapq 模块中找到 n 个具有恰当命名的 nsmallest 函数的最小项目;您需要提供一个自定义 key 函数来为每个项目提供分数;我们将为它使用 operator.itemgetter(1)(它将 return 元素 1 或每个 letter, score 对的 score

from operator import itemgetter
from heapq import nsmallest

result = nsmallest(5, pairs, key=itemgetter(1))
print(result)

打印出来

[('a', 8), ('b', 8), ('e', 12), ('h', 12), ('d', 13)]

要仅获取字母,只需添加:

letters = [ i[0] for i in result ]