python - 从列表中删除最小的数字

标签 python python-3.x min

我正在尝试编写一个函数来删除最小的数字,然后对列表中的剩余数字进行平均。有没有办法在不使用 sorted()sort() 的情况下从列表中删除最低的两个或更多数字?就像结合使用 min()range() 一样。

我目前拥有的:

lst = [90, 100, 95, 95]
lst.remove(min(lst))
print(sum(lst) / len(lst))

最佳答案

list.remove 删除列表中的第一个 匹配值。为了删除所有出现的当前最小数字,您必须调用它 list.count(min(list)) 次。

这是从 lst 中删除 n 个最小数字的函数,它不涉及 list.remove:

def remove_n_smallest(lst, n):
    for _ in range(n):
        m = min(lst)
        lst[:] = (x for x in lst if x != m)

这是您问题中的 lst 示例:

>>> remove_n_smallest(lst, 2)
>>> lst
[100]
>>> sum(lst) / len(lst)
100.0

关于python - 从列表中删除最小的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36827741/

相关文章:

Python 3.x - 如何有效地将对象数组拆分为更小的批处理文件?

python - 如何使用 [Insert into...select] 语句而不是 [Insert into...values] 方法在 postgres 中插入元组

python - 未正确附加矩阵

C++ vector 到 Python 3.3

Python Pandas 过滤;类型错误 : cannot convert the series to <class 'int' >

html - Safari 浏览器 html 输入类型最小最大验证不起作用

python-2.x - Python2 - 在 None 类型上使用最小值/最大值

MySQL CASE WHEN numb IS NULL 忽略记录 WHERE numb IS NOT NULL

python - 如何使用aiocoap库观察CoAP资源?

python套接字立即发送