简体   繁体   English

随机,非重复的2D列表Python

[英]Random, Non-Repeating 2D List Python

I have a program that generates a two dimensional list containing a set number of 2 dimensional co-ordinates within a certain range. 我有一个程序生成一个二维列表,其中包含一定范围内的一组二维坐标。 (It doesn't matter if the nested are lists or tuples) eg: (如果嵌套是列表或元组,则无关紧要)例如:

[[5, 0], [4, 6], [9, 7], [2, 9], [2, 6]]

The problem is that I wish for no two sublists to be equal while keeping the length of the outer list the same. 问题是我希望没有两个子列表相等,同时保持外部列表的长度相同。

i have tried using random.sample: 我尝试过使用random.sample:

pointx = random.sample(range(10),5)
pointy = random.sample(range(20),5)
points = list(zip(pointx,pointy))

where 10 is the x range, 20 is the y range and 5 is the amount of points: 其中10是x范围,20是y范围,5是点数:

[(1,0),(9,19),(8,13),(3,5),(0,14)]

However this method's maximum amount of points is only 10+20 where it clearly should be 10*20 because of the separate sample lists. 然而,由于单独的样本列表,此方法的最大点数仅为10 + 20,显然应为10 * 20。

While writing this, i have realised that: 写这篇文章时,我意识到:

point2D = []
point1D = random.sample(range(10*20),5)
[point2D.append(divmod(i,10)) for i in point1D]

This is a viable approach, but also clumsy, i was wondering whether there was a better solve possibly involving numpy. 这是一种可行的方法,但也很笨拙,我想知道是否有更好的解决可能涉及numpy。

Thanks in advance. 提前致谢。

Imagine a 2D grid of shape (10,20) with points at each integer points. 想象一下2D网格形状(10,20) ,每个整数点都有点。 Now, let's say we want to select 5 unique points on this grid. 现在,假设我们要在此网格上选择5唯一点。 That's all! 就这样! We translate this to NumPy. 我们将此翻译为NumPy。

Choose 5 unique indices from all possible 200 indices with : 从所有可能的200指数中选择5唯一指数:

idx = np.random.choice(200, size=5, replace=0)

Convert these indices into x and y coordinates that is speaking in terms of matrices terminology, get the row and column indices : 将这些索引转换为以矩阵术语表示的xy坐标,获取行和列索引:

row, col = np.unravel_index(idx,(10,20))

These would be the desired tuples. 这些将是所需的元组。

Let's put these two steps together for a complete code - 让我们将这两个步骤放在一起,以获得完整的代码 -

idx = np.random.choice(200, size=5, replace=0)
out = np.column_stack((np.unravel_index(idx,(10,20))))

Let's use a sample case - 我们来看一个样例 -

In [461]: idx = np.random.choice(200, size=5, replace=0)
     ...: out = np.column_stack((np.unravel_index(idx,(10,20))))
     ...: 

In [462]: out
Out[462]: 
array([[ 6, 18],
       [ 9, 17],
       [ 5,  7],
       [ 8,  2],
       [ 6, 12]])

Using numpy we can create all of the ordered pairs of (x,y) and then randomly select a number of pairs. 使用numpy,我们可以创建所有有序的(x,y)对,然后随机选择多个对。

# first create an array of all possible pairs from (0,0) to (9,19)
pairs = np.dstack(np.meshgrid(np.arange(10), np.arange(20))).reshape(-1,2)

# now select a random set of 25 of those pairs, which are unique
pairs[np.random.choice(np.arange(pairs.shape[0]), size=25, replace=False)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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