Skip to main content
 首页 » 编程设计

python之如何从整数列表中选择几个最大值

2025年05月04日15myhome

使用 Python 3.6 和 PyCharm,我从一个包含 12 个整数的初始化列表开始。这允许我对列表中的每个值应用一个随机数。然后我想从 12 个选项列表中选择最高的六个。这是我用来完成此操作的代码:

import random as rnd 
 
# Initialize with a list of 12 zeros 
options = [0, 0, 0, 0, 
           0, 0, 0, 0, 
           0, 0, 0, 0] 
 
# Loop through the list, replacing zeros with random numbers 
for i in range(len(options)): 
    options[i] = rnd.randint(3, 18) 
 
# Next, find the six max 
options_copy = options[:] 
largest_1 = max(options_copy)   # This seems very inefficient. 
options_copy.remove(largest_1)  #  
largest_2 = max(options_copy)   # What if I need the top 7,000 from  
options_copy.remove(largest_2)  # a list of 1 million? 
largest_3 = max(options_copy)   # 
options_copy.remove(largest_3)  # 
largest_4 = max(options_copy)   # 
options_copy.remove(largest_4)  # 
largest_5 = max(options_copy)   # 
options_copy.remove(largest_5)  # 
largest_6 = max(options_copy)   # 
options_copy.remove(largest_6)  # 
 
# Collect the best into it's own list. 
best = [largest_1, largest_2, largest_3, 
        largest_4, largest_5, largest_6] 

正如上面代码中的注释部分所说,这看起来效率很低。例如,假设我需要从 100 万个整数列表中找出前 7,000 个。是否有一种有效的循环机制可以达到相同的结果?

请您参考如下方法:

使用random.sample生成12个随机数的列表,然后反向排序并抓取前6个:

import random 
 
options = random.sample(range(3, 18), 12) 
print(options) 
 
best = sorted(options, reverse=True)[:6] 


更简洁:

best = sorted(random.sample(range(3, 18), 12), reverse=True)[:6]