简体   繁体   English

如何在不更改第一个列表顺序的情况下找到n个最小的数字?

[英]How can I find n smallest numbers without changing the order of the first list?

I intend to get the n smallest numbers in a list but keep the numbers in the same order they appear in the list. 我打算在列表中获得n最小的数字,但保持数字在列表中的显示顺序相同。 For example: 例如:

This is my list: 这是我的清单:

A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]

I like to get the first three lowest numbers as it has been ordered in the first list: 我喜欢获得前三个最低数字,因为它已在第一个列表中排序:

[1, 2, 0]

I do not want to sort the result as: 我不想将结果排序为:

[0, 1, 2]

I have tried: 我努力了:

heapq.nsmallest(3,A)

but i wonder if it is possible to retain this list as:[1, 2, 0] 但我想知道是否可以保留此列表为:[1、2、0]

By the way, I'm not a Python coder so thanks for the help in advance. 顺便说一句,我不是Python编码员,所以感谢您的提前帮助。

You can try this: 您可以尝试以下方法:

new_a = []
A=[1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
for a in A:
   if a not in new_a:
      new_a.append(a)
new_a = [i for i in new_a if i in sorted(new_a)[:3]]

Output: 输出:

[1, 2, 0]

You could use heapq.nsmallest() to get the n smallest elements from the list. 您可以使用heapq.nsmallest()从列表中获取n最小的元素。 Then use collections.Counter to create a multiset from that list which you can use to check which elements from the original list to include in the result, eg 然后使用collections.Counter从该列表中创建一个多集 ,您可以用来检查原始列表中要包含在结果中的元素,例如

>>> from heapq import nsmallest
>>> from collections import Counter
>>> A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
>>> n = 3    
>>> c = Counter(nsmallest(n, A))
>>> result = []
>>> for elem in A:
...     if c.get(elem, 0):
...         result.append(elem)
...         c[elem] -= 1
... 
>>> result
[1, 2, 0]

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

相关问题 找到列表中最小的 n 个数字的索引 - find the index of the smallest n numbers in a list 在不更改顺序的情况下找到最小的产品总和 - Find smallest sum of products without changing the order 给定一个随机顺序的数字列表,编写一个算法,该算法在 O(nlog(n)) 中工作以找到列表中第 k 个最小的数字 - Given a list of numbers in random order, write an algorithm that works in O(nlog(n)) to find the kth smallest number in the list 如何找到不能被 3 整除的最小 n 位数? - How can I find the smallest number of n digits that is not divisible by 3? 列表中最小的 n 个数字 - Smallest n numbers from a list 如何找到最小的N - How to find the smallest N 如何在列表中仅找到第一个最小的 integer - How to find only the first smallest integer in a list 如何更改此函数调用和算法,以在大小为n的列表中找到值最小的字符串。 没有最小功能 - How can I change this function call and algorithm to find the string with the smallest value in a list of size n. w/o the min function 如何从具有嵌套列表作为元素的列表中选择 n 个最小的数字 - How to pick n smallest numbers from a list with nested lists as elements 如何在每行数字中找到最小的数字? 不使用 min() - How to find the smallest number in each line of numbers? Without using min()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM