简体   繁体   中英

How to create a random Matrix in Python without duplicating integers?

My current solution to create a random matrix is

matrix = np.random.randint(low=n, high=m, size=(x,y))

Do you know a solution to not use an integer twice? Thank you

You could use np.random.choice .

np.random.choice(5, 3, replace=False)
# Output:
array([3,1,0]) # random

If you don't want to use random choice, you can always just randomly pop from a list of integers.

import numpy as np
# define values 
n = 0
m = 20 
x = 3
y = 4 

integer_list = [i for i in range(n, m)]  # assuming m is exclusive 
matrix = np.zeros((x,y))
for i in range(x):
    for j in range(y):
        matrix[i][j] = integer_list.pop(np.random.randint(0, len(integer_list)))

Edit: I wasn't able to get it working with random choice. When I use random choice it returns a single value, rather than a list of values. A more efficient solution would be to simply shuffle the list.

import numpy as np
import random
# define values 
n = 0
m = 20 
x = 3
y = 4 

integer_list = [i for i in range(n, m)]  # assuming m is exclusive
random.shuffle(integer_list)
matrix = np.zeros((x,y))
for i in range(x):
    for j in range(y):
        matrix[i][j] = integer_list.pop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM