Import matrix from text file using python

后端 未结 1 1456
不思量自难忘°
不思量自难忘° 2021-01-24 17:59

I have two text files that have matrices written in them(not numpy matrices, so its a list of lists). These matrices are written in string format, so the text file looks like th

相关标签:
1条回答
  • 2021-01-24 18:41

    You could make use of the ast module:

    import ast
    
    strArray =  "[[1,2,3],[3,4,5],[6,7,8]]"
    
    # evaluates the array in string format and converts it to a python array object
    array = ast.literal_eval(strArray)
    

    note: For multiple nested arrays like you have, literal_eval will most likely convert the string into a tuple with nested arrays as elements. Just keep that in mind as you use this module.

    0 讨论(0)
提交回复
热议问题