Andy
Andy

Reputation: 829

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?

Upvotes: 1

Views: 77

Answers (2)

Austin
Austin

Reputation: 26039

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]

Upvotes: 4

salparadise
salparadise

Reputation: 5805

You can do this with a list comprehension and slice to get the first 6 values after sorting:

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

Upvotes: 2

Related Questions