Home  >  Q&A  >  body text

matrix - python怎么通过input获取矩阵

最近在学随机过程,中间要计算矩阵,矩阵相乘太麻烦了,所以想用编程实现,也顺便练下手。
基本功能已经实现,但是只能自己在程序里事先把数组输进去,所以想问一下怎样才可以通过input函数直接过去矩阵。

看了网上其他人的办法,都是这样的
输入
>>1 2 3 4 5

通过是split(' ')来获取得到['1','2','3''4','5']

但是我想要的是这样的的效果,这样感觉美观一些。
输入:
>>[ [1,2,3],[1,2,3] ]

先谢谢啦

PHP中文网PHP中文网2741 days ago867

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 17:47:18

    A comparison is not safe but the immediate solution to the problem is:

    matrix = input(">>")
    matrix = eval(matrix)
    print(matrix)

    Result:

    >>[ [1,2,3], [1,2,3] ]
    [[1, 2, 3], [1, 2, 3]]

    P.S. You can consider using a file to input

    For example:

    matrix a
    1 2 3
    1 2 3

    Supplement: If you want to use a ready-made library to process matrices in Python, numpy is a good choice.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:47:18

    Isn’t it best to use Matlab to calculate matrices?

    reply
    0
  • Cancelreply