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

时间:2017-12-06 11:40:19

标签: python python-3.x list sorting

我打算在列表中获取index个最小数字,但保持数字与它们在列表中显示的顺序相同。例如:

这是我的清单:

index

我喜欢在第一个列表中订购前三个最低数字:

select a.day, a.counts as 'NY', b.counts as 'LA' from 
(select day, count(id) as counts from index where city='NY' GROUP BY DAY) as a
left join
(select day, count(id) as counts from index where city='LA' GROUP BY DAY) as b
on (a.day = b.day)
order by field (a.day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

我不想将结果排序为:

index

我试过了:

index

但我想知道是否可以将此列表保留为:[1,2,0]

顺便说一句,我不是Python编码器,所以感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

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]]

输出:

[1, 2, 0]

答案 1 :(得分:2)

您可以使用heapq.nsmallest()从列表中获取n个最小元素。然后使用collections.Counter从该列表创建 multiset ,您可以使用该列表检查原始列表中哪些元素包含在结果中,例如

>>> 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]
相关问题