如何在Python中生成带有重复数字的随机列表 [英] How do I generate a random list in Python with duplicates numbers

查看:1123
本文介绍了如何在Python中生成带有重复数字的随机列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以几天前我才开始用Python编程.现在,我试图制作一个生成随机列表的程序,然后选择重复元素.问题是,我的列表中没有重复的数字.

So I just started programming in Python a few days ago. And now, im trying to make a program that generates a random list, and then, choose the duplicates elements. The problem is, I dont have duplicate numbers in my list.

这是我的代码:

import random

def generar_listas (numeros, rango):
    lista = [random.sample(range(numeros), rango)]
    print("\n", lista, sep="")
    return
def texto_1 ():
    texto = "Debes de establecer unos parámetros para generar dos listas aleatorias"
    print(texto)
    return

texto_1()
generar_listas(int(input("\nNumero maximo: ")), int(input("Longitud: ")))

例如,我为random.sample选择20和20,它将为我生成一个从0到20的列表,但位置随机.我想要一个带有随机数且重复的列表.

And for example, I choose 20 and 20 for random.sample, it generates me a list from 0 to 20 but in random position. I want a list with random numbers and duplicated.

推荐答案

您想要的非常简单.您要生成一个随机数字列表,其中包含一些重复项.如果您使用诸如numpy之类的方法,则这样做很容易.

What you want is fairly simple. You want to generate a random list of numbers that contain some duplicates. The way to do that is easy if you use something like numpy.

  • 生成一个0到10的列表(范围).
  • 从该列表中随机抽样(替换).

赞:

import numpy as np
print np.random.choice(10, 10, replace=True)

结果:

[5 4 8 7 0 8 7 3 0 0]

如果要排序列表,只需使用内置函数"sorted(list)"

If you want the list to be ordered just use the builtin function "sorted(list)"

sorted([5 4 8 7 0 8 7 3 0 0])
[0 0 0 3 4 5 7 7 8 8]

如果您不想使用numpy,则可以使用以下命令:

If you don't want to use numpy you can use the following:

print [random.choice(range(10)) for i in range(10)]
[7, 3, 7, 4, 8, 0, 4, 0, 3, 7]

这篇关于如何在Python中生成带有重复数字的随机列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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