繁体   English   中英

从列表中删除最低值

[英]dropping the lowest values from a list

我正在尝试编写一个Python程序,该程序将从列表中删除最低值的25%,并(返回原始未排序的列表)。 例如;

Input : [1,5,6,72,3,4,9,11,3,8] 
Output : [5,6,72,4,9,11,8]

我试着做:

l = [1,5,6,72,3,4,9,11,3,8]

def drop(k):
     while len(l)!=0 and k > 0:
        k = k - 1
        l.sort(reverse = True)
        l.pop()
 return l

k = math.ceil(len(l) * 0.25)
drop (k)

它返回[72、11、9、8、6、5、4],但是有没有排序的方法吗?

您可以使用heapq并保持弹出元素,直到删除25%的容器为止。 然后,过滤原始列表的内容

import heapq, copy
s = [1,5,6,72,3,4,9,11,3,8] 
new_s = copy.deepcopy(s)
heapq.heapify(s)
count = 0
last_items = set()
while count/float(len(new_s)) <= 0.25:
  last_items.add(heapq.heappop(s))
  count += 1

final_s = [i for i in new_s if i not in last_items]

输出:

[5, 6, 72, 4, 9, 11, 8]

您不需要反向排序并找到最小的元素。 在列表l上使用min ,它从l返回最小值,并使用l.remove方便地删除。

import math
l = [1,5,6,72,3,4,9,11,3,8]

def drop(k):
     while len(l)!=0 and k > 0:
        k = k - 1
        l.remove(min(l))
     return l

k = math.ceil(len(l) * 0.25)
print(drop (k))
# [5, 6, 72, 4, 9, 11, 8]

一种方法是这样做非常慢,特别是对于较长的列表!

quart_len = int(0.25*len(l))
for i in range(quart_len):
     l.remove(min(l))

一种更快的方法:

import numpy as np
from math import ceil

l = [1,5,6,72,3,4,9,11,3,8]
sorted_values = np.array(l).argsort()
l_new = [l[i] for i in range(len(l)) if i in sorted_values[int(ceil(len(l)/4.)):]]

另一种方法:

l = np.array(l)
l = list(l[l > sorted(l)[len(l)/4]])

这个问题有O(n)个解决方案。 其中的一个introselect在numpy的partitionargpartition函数中实现:

>>> data = [1,5,6,72,3,4,9,11,3,8] 
>>> 
>>> k = int(round(len(data) / 4))
>>>
>>> import numpy as np
>>> dnp = np.array(data)
>>> drop_them = np.argpartition(dnp, k)[:k]
>>> keep_them = np.ones(dnp.shape, dtype=bool)
>>> keep_them[drop_them] = False
>>> result = dnp[keep_them].tolist()
>>> 
>>> result
[5, 6, 72, 4, 9, 11, 3, 8]

请注意,此方法保留3 s中的一个,并丢弃另一个s,以便精确地在k元素上进行拆分。

相反,如果您希望对所有3都一视同仁,则可以

>>> boundary = np.argpartition(dnp, k)[k]
>>> result = dnp[dnp > dnp[boundary]]
>>> 
>>> result
array([ 5,  6, 72,  4,  9, 11,  8])
l1=[1,5,6,72,3,4,9,11,3,8]
l2=sorted(l1)
ln=round(len(l1)*0.25)
[i for i in l1 if i not in l2[ln+1:]]

输出:

[5, 6, 72, 4, 9, 11, 8]

暂无
暂无

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

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