在python中使用random.randint从列表中随机选择 [英] randomly choose from list using random.randint in python

查看:125
本文介绍了在python中使用random.randint从列表中随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 random.randint() 在 python 中选择列表中给出的随机名称.

我想打印该列表中的 5 个名字.其实我知道如何使用 random.randint() 来表示数字.但我不知道如何从给定的列表中选择随机名称.

我们不允许使用 random.choice.

请帮帮我

解决方案

>>>人口 = 范围(10)

你可以使用random.sample吗?

<预><代码>>>>名称 = random.sample(人口,5)>>>名字[4, 0, 1, 2, 8]

单独使用 random.randint 会更困难,但如果你必须这样做,我会这样做:

<预><代码>>>>名称 = [population[random.randint(0, len(population)-1)] for x in range(5)]>>>名字[2, 8, 6, 6, 9]

但显然这是替换.如果您不想替换,则需要一些更复杂的代码.例如一个函数:

def custom_sample(population, count):姓名 = []已经使用 = []对于范围内的 x(计数):temp_index = random.randint(0, len(population)-1)而 temp_index 在 already_used 中:temp_index = random.randint(0, len(population)-1)名称.附加(人口[temp_index])already_used.append(temp_index)返回名称

所以:

<预><代码>>>>名称 = custom_sample(人口,5)>>>名字[7, 4, 8, 3, 0]

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]

这篇关于在python中使用random.randint从列表中随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆