如何生成 0 到 31 之间的随机整数对?

How to generate random integer pairs between 0 and 31?

如题所示,我想生成100对随机整数,如(1, 0)(1, 31)(5, 7)(3, 19)等。取值范围是0到31。同时希望每对在100对中只出现一次,即每对的值都不同。

那么我怎样才能在 Python 中实现它?

补充:

准确的说,我要的是一个二维数组,它的形状是(100,2)。每行都必须是唯一的。

您可以使用 random.sample:

import random

pool = range(32)
random.sample(pool, 2)
# [7, 28]
random.sample(pool, 2)
# [15, 3]
import numpy as np

pool_ = [ (i,j) for i in range(32) for j in range(32) ]
# List of all pairs

pool = np.zeros( len(pool_), dtype = tuple ) # Create an np.array of tuples

pool[:] = pool_  # fill it with pool_

selected = np.random.choice( pool, replace = False, size =100 )
# select 100 random choices from the pool, without replacement

print( selected )
# [(0, 22) (4, 30) (2, 25) (4, 19) (6, 6) (17, 22) (18, 14) (12, 27) (30, 6)
# (22, 18) (13, 5) (23, 22) (27, 17) (17, 26) (26, 22) (7, 15) (15, 27)
# (4, 31) (15, 1) (28, 22) (25, 16) (25, 15) (7, 12) (7, 21) (26, 14)
# (9, 9) (8, 0) (26, 27) (14, 14) (22, 0) (4, 18) (12, 3) (25, 9) (22, 31)
# (11, 6) (23, 7) (18, 19) (19, 25) (23, 19) (25, 5) (5, 19) (3, 24)
# (30, 0) (18, 10) (20, 4) (24, 11) (13, 28) (10, 5) (6, 7) (11, 7)
# (25, 24) (23, 18) (15, 10) (14, 7) (11, 11) (9, 23) (13, 8) (3, 28)
# (28, 3) (21, 3) (24, 31) (29, 27) (24, 28) (17, 6) (30, 19) (25, 28)
# (12, 17) (13, 15) (3, 11) (14, 1) (12, 6) (17, 17) (23, 2) (24, 18)
# (25, 11) (3, 26) (6, 2) (0, 28) (5, 12) (4, 1) (23, 17) (29, 23) (22, 17)
# (24, 15) (2, 5) (28, 11) (19, 27) (9, 20) (1, 11) (30, 5) (30, 21)
# (30, 28) (18, 31) (5, 27) (30, 11) (16, 0) (24, 16) (12, 30) (25, 25)
# (16, 22)]

我还没有彻底测试过,但是 replace = False 在 random.choice 中每个选择都应该是唯一的。

到return一个二维数组

import numpy as np

pool_ = [ (i,j) for i in range(32) for j in range(32) ]
# List of all pairs

pool_ix = np.arange( len(pool_) ) # index by row

pool = np.array(pool_) # 2D pool

selected_ix = np.random.choice( pool_ix, replace = False, size =100 )

pool[selected_ix, : ]  # Select all of each selected row.

# array([[12, 19],
#        [ 6, 23],
#        [ 2,  3],
#        [ 5, 20],
#           :::
#        [20,  3],
#        [24, 20],
#        [ 1, 28]])