简体   繁体   English

在 Python 中构造唯一值从 1 到 n 的 nxn 矩阵

[英]Construct n x n matrix with unique value from 1 to n in Python

I have two lists in Python我在 Python 中有两个列表

P = [P1, P2..... Pn] , D = [D1, D2..... Dn] . P = [P1, P2..... Pn] , D = [D1, D2..... Dn]

I want to create a matrix in such a way that each cell should contain a value from 1 to n .我想以这样一种方式创建一个矩阵,即每个单元格都应该包含一个从1n的值。 Cell value should be unique both in the row and column and each time it should generate different combination.单元格值在行和列中都应该是唯一的,并且每次它应该生成不同的组合。

Sample output is shown below for n=3 and arbitrary P and D both of size 3.示例 output 如下所示, n=3且任意PD的大小均为 3。

Anyone has any idea of generating such matrix?任何人都知道生成这样的矩阵吗?

n x n 矩阵

You can do the following:您可以执行以下操作:

import random

def createMatrix(n):
    firstRow = random.sample(range(n),n)
    permutes = random.sample(range(n),n)
    return list(firstRow[i:]+firstRow[:i] for i in permutes)


N = 5
m = createMatrix(N)
print(m)

Which for the case of N=5 gives (after converting to numpy array for the printing):对于N=5的情况,哪个给出(在转换为numpy数组进行打印之后):

[[4 0 1 2 3]
 [1 2 3 4 0]
 [3 4 0 1 2]
 [0 1 2 3 4]
 [2 3 4 0 1]]

In the case of values starting from 1 the correction to the function is:对于从 1 开始的值,对 function 的更正为:

def createMatrix(n):
    firstRow = random.sample(range(1, n + 1),n)
    permutes = random.sample(range(1, n + 1),n)
    return list(firstRow[i:]+firstRow[:i] for i in permutes)

Solution without modules and by pattern.没有模块和模式的解决方案。 You can input anything you want in P1, and will give you a matrix您可以在 P1 中输入您想要的任何内容,并会给您一个矩阵

P1 = list(range(1, 101))

matrix_len = len(P1)
w, h = matrix_len, matrix_len
matrix = [[None for x in range(w)] for y in range(h)]
counter=0
for i in range(matrix_len):
    for j in range(matrix_len):
        matrix[counter][j] = i
        counter +=1
        if counter == matrix_len:
            counter= 0
    counter +=1

print(matrix)

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

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