You can use np.random.choice
np.random.default_rng().choice
with replace=False
to ensure uniqueness.
import numpy as np
first = np.random.choice(np.arange(1000, dtype=int), 5, replace=False) # replace=False ensures uniqueness
# first = array([645, 543, 233, 93, 420])
second = np.random.choice([1, 2], 5)
# second = array([1, 1, 2, 1, 2])
Using the np.array
to combine the two and taking the trasnpose:
np.array((first, second)).T.tolist()
# [[645, 1], [543, 1], [233, 2], [93, 1], [420, 2]]
Update:
Based on the comment by @Sam Mason and according to this thread, seems like the preferred way since numpy 1.17 is to use rng = np.random.default_rng()
.
So, the variable first
shall be changed to:
rng = np.random.default_rng()
first = rng.choice(np.arange(1000, dtype=int), 5, replace=False)
Timing Comparison
This is a rough timing comparison for two large values. If a proper comparison is needed, you need to run this for many combinations of the array length and the range to pick from. Feel free to edit this as the new answers appear.
length, max_val = 100000, 10000000
%timeit op(length, max_val)
%timeit akilat90(length, max_val)
%timeit Reti43_np(length, max_val)
%timeit Reti43_p(length, max_val)
%timeit Shivam_Roy(length, max_val)
# 1 loop, best of 5: 392 ms per loop
# 10 loops, best of 5: 45.4 ms per loop
# 1 loop, best of 5: 13.8 s per loop
# 1 loop, best of 5: 261 ms per loop
# 1 loop, best of 5: 364 ms per loop
Code to reproduce:
def op(length, max_val):
"""
[0, max_val) range is considered to get the first values
"""
if max_val < length:
raise ValueError("Can't ensure uniqueness")
return [[[random.randint(1,max_val), random.randint(0,2)] for i,j in zip(range(1), range(1))][0] for i in range(length)]
def akilat90(length, max_val):
if max_val < length:
raise ValueError("Can't ensure uniqueness")
value_range = np.arange(max_val)
rng = np.random.default_rng()
first = rng.choice(value_range, length, replace=False)
second = rng.choice([1, 2], length)
return np.array((first, second)).T.tolist()
def Reti43_np(length, max_val):
if max_val < length:
raise ValueError("Can't ensure uniqueness")
a = np.arange(max_val)[:,None]
np.random.shuffle(a)
a = a[:length]
b = np.random.randint(0, 3, (length, 1))
out = np.hstack([a, b])
return out
def Reti43_p(length, max_val):
if max_val < length:
raise ValueError("Can't ensure uniqueness")
a = random.sample(range(1, max_val + 1), length)
b = [random.randint(0, 2) for _ in range(length)]
# If you want a list of lists instead `[[first, second] for first, second in zip(a, b)]`
return list(zip(a, b))
def Shivam_Roy(length, max_val):
if max_val < length:
raise ValueError("Can't ensure uniqueness")
rand_list = random.sample(range(0, max_val), length)
return [[[rand_list[x], random.randint(0,2)] for i,j in zip(range(1), range(1))][0] for x in range(length)]