Python读取一个字符串形式的矩阵,并存入矩阵中去。

输入:‘[[0,0,0,0],[1,0,0,1],[1,1,1,0]]’ 注意这个Python读进来是字符串。

输出:一个矩阵 [[0, 0, 0, 0], [1, 0, 0, 1], [1, 1, 1, 0]]

思路:先把所有数字拿出来,变成一个矩阵,然后我们找到矩阵的列数,然后重新reshape一下。

import sys
import numpy as np
string = sys.stdin.readline().strip()

arr = []
count = 0
for i in string:
    try:
        arr.append(int(i))
    except:
        if i == '[':
            count += 1
        pass


cols = int(len(arr)/count)

grid = []
cur = []

for i in arr:
    if len(cur)<=cols:
        cur.append(i)
    else:
        grid.append(cur)
        cur  = []
        cur.append(i)
grid.append(cur)

print(grid)

猜你喜欢

转载自blog.csdn.net/listep/article/details/82798563