简体   繁体   中英

randomly choose from list using random.randint in python

How to use random.randint() to select random names given in a list in python.

I want to print 5 names from that list. Actually i know how to use random.randint() for numbers. but i don't know how to select random names from a given list.

we are not allowed to use random.choice .

help me please

>>> population = range(10)

Are you allowed to use random.sample ?

>>> names = random.sample(population, 5)
>>> names
[4, 0, 1, 2, 8]

Using solely random.randint would be more difficult, but if you must do so, I'd do something like this:

>>> names = [population[random.randint(0, len(population)-1)] for x in range(5)]
>>> names
[2, 8, 6, 6, 9]

But obviously this is with replacement. If you don't want replacement, you'd need some more complicated code. For example, a function:

def custom_sample(population, count):
    names = []
    already_used = []
    for x in range(count):
        temp_index = random.randint(0, len(population)-1)
        while temp_index in already_used:
            temp_index = random.randint(0, len(population)-1)
        names.append(population[temp_index])
        already_used.append(temp_index)
    return names

So:

>>> names = custom_sample(population, 5)
>>> names
[7, 4, 8, 3, 0]

This will not guarantee no repeats, since random.choice is better for that.

import random
names = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
print([names[random.randint(0, len(names)-1)] for i in range(5)])

The simplest way to select a random item from the list is to use using random.randint() as below,

Say for instance your list is:

list_1 = ['cat', 'amusement park', 'bird watching']

and you want to print an item from the list randomly then,

import random
print(list_1[random.randint(0,2)])

If you want to get a random element from a list using random.randint() , below is an option

list_name = [...]                                 # a sample list
size = len(list_name)                             # finding the length of the list
random_elemet = list_name[random.randint(0,size)] # get a random element

Yes, for repeat sample from one population, @MaxLascombe's answer is OK. If you do not want tiles in samples, you should kick the chosen one out. Then use @MaxLascombe's answer on the rest of the list.

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