简体   繁体   English

如何从 python 中保存为文本文件的 arrays 列表中导入和提取元素

[英]How to Import and extract elements from a list of arrays saved as a text file in python

I have a.txt file, which is a list of arrays.我有一个 .txt 文件,它是 arrays 的列表。 I want to import that file and extract elements of that list of arrays and work with them.我想导入该文件并提取 arrays 列表中的元素并使用它们。 when I use当我使用

with open('filename.txt') as f:
        list1 = eval(f.read())

which works well when I want to import a list of numbers, does not work when the elements are arrays.当我想导入数字列表时效果很好,当元素是 arrays 时不起作用。 It gives它给

NameError: name 'array' is not defined

Problem is perhaps with the eval() function not working well with arrays?问题可能是 eval() function 不能与 arrays 一起工作? Could you help me import this list of arrays?你能帮我导入这个 arrays 列表吗?

If the file content is, for example:如果文件内容是,例如:

array([1,2,3])

...then... ...然后...

from numpy import array

with open('filename.txt') as f:
    a = eval(f.read())
    print(a)
    print(type(a))

...will produce... ...会产生...

[1 2 3]
<class 'numpy.ndarray'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM