如何在矩阵中插入一系列数字?

2024-04-27 02:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个9x9矩阵:

x=[
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
]

我想插入一系列数字,比如:

aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060

我希望能够将每个数字放到矩阵的一个单独位置,但我有点难以解决这个问题


Tags: 矩阵数字aux
2条回答
  • 这一行代码通过9拆分并再次映射到整数来工作
  • for i in range(0, len(str(aux)), 9)这将迭代大小为9的块
  • list(map(int, aux[i,i+9]))这将把字符串中的每个字符映射到int,并创建它的列表。有关更多信息,请参见python中的map函数
  • 以上两个步骤结合在列表理解中,将为您提供列表列表
aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060 # assumption 81 digit number or string ?
m = [list(map(int, str(aux)[i:i+9])) for i in range(0, len(str(aux)), 9)]
print(m)
  • 输出
[[9, 0, 0, 0, 0, 0, 0, 0, 1],
 [0, 5, 1, 2, 0, 0, 0, 3, 0],
 [0, 0, 0, 9, 8, 0, 0, 0, 0],
 [6, 8, 0, 7, 4, 0, 0, 0, 0],
 [7, 3, 0, 0, 0, 0, 9, 0, 8],
 [0, 1, 0, 0, 5, 8, 6, 7, 0],
 [0, 0, 8, 1, 0, 0, 0, 0, 0],
 [0, 0, 2, 0, 0, 7, 0, 9, 0],
 [1, 9, 0, 0, 0, 4, 0, 6, 0]]

使用Python 3.7编写的以下代码将为您完成这项工作:

if __name__ == "__main__":
    # size of the array n x n
    n = 9

    # the n x n array
    x = [[0]*n]*n

    # the input number converted as a string
    aux = "900000001051200030000980000680740000730000908010058670008100000002007090190004060"

    k = 0
    for i in range(0,n):
        for j in range(0,n):
            x[i][j] = aux[k]
            k = k + 1

然后,要打印矩阵x,需要执行以下操作:

import numpy as np

# print the modified array x
print(np.matrix(x))

它给出了输出:

[['9' '0' '0' '0' '0' '0' '0' '0' '1']
 ['0' '5' '1' '2' '0' '0' '0' '3' '0']
 ['0' '0' '0' '9' '8' '0' '0' '0' '0']
 ['6' '8' '0' '7' '4' '0' '0' '0' '0']
 ['7' '3' '0' '0' '0' '0' '9' '0' '8']
 ['0' '1' '0' '0' '5' '8' '6' '7' '0']
 ['0' '0' '8' '1' '0' '0' '0' '0' '0']
 ['0' '0' '2' '0' '0' '7' '0' '9' '0']
 ['1' '9' '0' '0' '0' '4' '0' '6' '0']]

相关问题 更多 >