简体   繁体   中英

How do I choose several maximum values from a list of integers?

Using Python 3.6 with PyCharm, I start with an initialized list of 12 integers. This allows me to apply a random number to each value in the list. I then want to select the highest six from the list of 12 options. Here is the code I've used to accomplish this:

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]

As the commented section in the above code says, this seems very inefficient. For example, suppose I needed to find the top 7,000 from a list of 1 million integers. Is there an effective loop mechanism that achieves the same result?

Use random.sample to generate list of 12 random numbers and then sort in reverse and grab first 6:

import random

options = random.sample(range(3, 18), 12)
print(options)

best = sorted(options, reverse=True)[:6]


More concisely:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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