[英]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.