How do I get a list of random numbers, guaranteeing them at least once?

I'm trying to have a list of numbers from 1 to 10 with many occurrences, so I started by using the following code:

list(range(1,11))

      

However, he only gives each number once. I need to have an output in double size, half of which has randomly ordered numbers and half of which has random numbers in a given range, for example:

[1,2,3,4,5,6,7,8,9,10,3,4,2,7,5,7,5,2,8,9]

      

My approach:

1) Generating a random list

a = random.randint(0,9)

      

2) Combining with range output

b = list(range(1,11))
result = a+b

      

Can this be used in another way?

+3


source to share


3 answers


Use built-in random

.



import random

my_list = list(range(1,11))
for i in range(10):
    my_list.append(random.randint(0, 10))

print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, 5, 10, 8, 6, 10, 6, 5, 6, 6]

      

+2


source


import random

l = [x for x in range(11)] + [random.randint(0, 10) for x in range(11)]

      

edit If you want the second half of the list to contain only items from the first half, but in random order



a = [x for x in range(11)]
b = a[:]
random.shuffle(b)
a.extend(b)

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 7, 4, 10, 1, 5, 9, 3, 0, 6, 2, 8]

      

+3


source


What happened with:

import random

your_array = list(range(1, 11)) + random.sample(range(1, 11), 10)  
#  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 7, 8, 2, 1, 9, 5, 10, 6, 4]

      

Per second read ... If you want to repeat in the second part, you can do it like:

your_array = list(range(1, 11)) + [random.randrange(1, 11) for _ in range(10)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 8, 1, 5, 1, 10, 5, 2, 10]

      

+2


source







All Articles