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

时间:2018-11-24 05:41:22

标签: python python-3.x pycharm

使用带有PyCharm的Python 3.6,我从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]

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

您可以使用列表推导和切片来执行此操作,以便在排序后获得前6个值:

sorted((rnd.randint(3, 18) for _ in range(12)), reverse=True)[:6]