import an array in python

后端 未结 5 1960
清歌不尽
清歌不尽 2020-12-28 19:13

How can I import an array to python (numpy.arry) from a file and that way the file must be written if it doesn\'t already exist.

For example, save out a matrix to a

5条回答
  •  梦谈多话
    2020-12-28 20:09

    In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:

    import numpy as np
    foods = ['grape', 'cherry', 'mango']
    filename = "./outfile.dat.npy"
    np.save(filename, np.array(foods))
    z = np.load(filename).tolist()
    print("z is: " + str(z))
    

    This prints:

    z is: ['grape', 'cherry', 'mango']
    

    Which is stored on disk as the filename: outfile.dat.npy

    The important methods here are the tolist() and np.array(...) conversion functions.

提交回复
热议问题