2

When working with random module

In [1]: from random import *                                                                                                  

In [2]: sample([10, 20, 30, 40, 50], k=4)                                                                                     
Out[2]: [20, 30, 50, 10]

the result is not randomly completely

How could produce a result as

In [2]: sample([10, 20, 30, 40, 50], k=4)                                                                                     
Out[2]: [20, 20, 20, 10]

to generate duplicated elements.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Alice
  • 1,360
  • 2
  • 13
  • 28
  • 1
    https://stackoverflow.com/questions/39379515/how-do-i-generate-a-random-list-in-python-with-duplicates-numbers Here you go, your question is answered already :) – Bear-K Mar 20 '19 at 09:17

4 Answers4

2

sample is the wrong tool, as you've seen. Instead, you could use choices:

choices([10, 20, 30, 40, 50], k=4)     
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You can try use Python's standard random.choices where you can specify optional weights for each element you generate. Docs:

choices([10, 20, 30, 40, 50], weights=[5, 50, 10, 15, 10], k=4)

Output

[40, 20, 50, 20]
devaerial
  • 2,069
  • 3
  • 19
  • 33
1

You can use numpy.random.choice

import numpy as np

x = [10, 20, 30, 40, 50]

print(np.random.choice(x, 4, replace=True))

Output:

[50 50 30 30] 
Sociopath
  • 13,068
  • 19
  • 47
  • 75
1

What you're looking for is random.choices - New in Python version 3.6. - The function definition is below; and you can read more here.

random.choices(population, weights=None, *, cum_weights=None, k=1)

You can assign weights in order to give a specific element precedence over others. - Although I believe the example below would satisfy your needs.

Example

import random

random.choices([1, 2, 3, 4], k=4)

Alternatively in older Python versions you can use random.choice as shown below; although it simply support one argument, a sequence.

Example

import random

population = [1, 2, 3, 4, 5]

def choices(population, k=1):
    return [random.choice(population) for _ in range(k)] if k > 1 else random.choice(population)

choices(population, k=5)

Output

[2, 4, 2, 5, 1]
Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34