python - 解析二维数组中的字符串推送值

标签 python numpy

我想将一串数字解析为二维方阵/矩阵,例如第一个数字标识矩阵的大小

输入45621797533863034 这里第一个数字 4 标识其 4x4 矩阵,其余是值。

所以数组应该是

5 6 2 1
7 9 7 5
3 3 8 6
3 0 3 4

最佳答案

IIUC:

s = '45621797533863034'
s = np.array(list(s))
s[1:].reshape(int(s[0]), -1)

输出:

array([['5', '6', '2', '1'],
       ['7', '9', '7', '5'],
       ['3', '3', '8', '6'],
       ['3', '0', '3', '4']], dtype='<U1')

如果你希望输出为数字,你可以传入正确的数据类型:

s = '45621797533863034'
s = np.array(list(s), dtype=np.uint8)
s[1:].reshape(s[0],-1)

输出:

array([[5, 6, 2, 1],
       [7, 9, 7, 5],
       [3, 3, 8, 6],
       [3, 0, 3, 4]], dtype=uint8)

关于python - 解析二维数组中的字符串推送值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59181658/

相关文章:

Python二维查询..

python - 字符串子串的顺序统计

Python - 如何使用 obspy 模块将计数转换为 m/s

numpy - 从 pandas.DataFrame 绘制引导样本

Python - 将数组列表转换为二维数组

python - 如何使用 matplotlib 实时绘制条形图

python - 在用 python 生成的图形中添加一些数字

python - 以正确的方式更新 Pandas Dataframe 中的列值

python - `del` 能让 Python 更快吗?

python - 如何使用Numpy解决Type Error