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.

This is my code:

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: ")))

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.

解决方案

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.

Generate a list (range) of 0 to 10.

Sample randomly (with replacement) from that list.

Like this:

import numpy as np

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

Result:

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

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]

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值