Skip to main content
 首页 » 编程设计

python之消除 python 列表中的 n 个最高值

2025年05月04日15over140

我有一个如下所示的列表:

List = [83, 36, 44, 66, 78, 34, 78, 55, 89, 100, 97] 

丢弃列表中两个最高值的最简单方法是什么?

Pandas 是一条出路吗?像这样的东西:

import pandas as pd 
df = pd.DataFrame( 
    List,  
    index =['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'],  
    columns =['Names'] 
) 

还有类似的东西:

df = df.nsmallest(len(List)-2, 'Names') 

我觉得非常乏味的事情是在 pandas dataframe IE 中手动定义 index,手动输入 ['1', '2', '3', '4 ', '5', '6', '7', '8', '9', '10', '11'] for 循环可以做到这一点吗?

谢谢

请您参考如下方法:

鉴于问题的简单性,我没有看到使用 Pandas 的明确理由:

my_list = [83, 36, 44, 66, 78, 34, 78, 55, 89, 100, 97] 
n = 2 
print (sorted(my_list)[:len(my_list)-n]) 

输出

[34, 36, 44, 55, 66, 78, 78, 83, 89] 

所使用的技术称为切片,可以根据我们的需要轻松地切割列表。

下面是一个简单的示例,可以快速了解其工作原理:

a[start:stop]  # items start through stop-1 
a[start:]      # items start through the rest of the array 
a[:stop]       # items from the beginning through stop-1 
a[:]           # a copy of the whole array 

我刚刚阅读了来自@EliasStrehle 的评论,其中有一个很好的观点,即可能需要将原始列表作为一个整体(完整副本)保留。

如果我们想保留原始列表的副本:

my_list = [83, 36, 44, 66, 78, 34, 78, 55, 89, 100, 97] 
new_list = sorted(my_list) 
n = 2 
new_list = new_list[:len(new_list)-n] 
print("Original list:") 
print(my_list) 
print("New list:") 
print (new_list) 

输出

Original list: 
[83, 36, 44, 66, 78, 34, 78, 55, 89, 100, 97] 
New list: 
[34, 36, 44, 55, 66, 78, 78, 83, 89] 

如果我们只想保持列表顺序:

my_list = [83, 36, 44, 66, 78, 34, 78, 55, 89, 100, 97] 
n = 2 
for times in range(n): 
    my_list.remove(max(my_list)) 
print(my_list) 
 
 
# Another way of writing the same thing in a more cryptic / minimalistic oneliner 
l = [83, 36, 44, 66, 78, 34, 78, 55, 89, 100, 97] 
[l.remove(max(l)) for _ in range(2)] 

输出

[83, 36, 44, 66, 78, 34, 78, 55, 89]