Python 将numpy数组的内容和几个属性打印到文本文件中
我有一个数组。我的任务是打印出数组及其形状、大小、项目大小、尺寸和数据类型名称。输出应该是一个文本文件-每个属性都应该位于新行上 当我尝试使用以下代码时,会出现错误:Python 将numpy数组的内容和几个属性打印到文本文件中,python,numpy,text,Python,Numpy,Text,我有一个数组。我的任务是打印出数组及其形状、大小、项目大小、尺寸和数据类型名称。输出应该是一个文本文件-每个属性都应该位于新行上 当我尝试使用以下代码时,会出现错误: File "<ipython-input-76-f4d4f45285be>", line 1, in <module> print(a.shape) AttributeError: 'NoneType' object has no attribute 'shape' 我做错了什么,如何修复我
File "<ipython-input-76-f4d4f45285be>", line 1, in <module>
print(a.shape)
AttributeError: 'NoneType' object has no attribute 'shape'
我做错了什么,如何修复我的输出?
print
只打印传入标准输出的值,然后返回None
。如果要访问属性,只需在不打印的情况下执行即可:
import numpy as np
a = np.arange(15).reshape(3,5)
shape = a.shape
size = a.size
itemsize = a.itemsize
ndim = a.ndim
dtype = a.dtype
print(a)
print(a.shape)
print(a.size)
print(a.itemsize)
print(a.ndim)
print(a.dtype)
如果要打印
,请不要指定打印
的返回值:
import numpy as np
a = np.arange(15).reshape(3,5)
shape = a.shape
size = a.size
itemsize = a.itemsize
ndim = a.ndim
dtype = a.dtype
print(a)
print(a.shape)
print(a.size)
print(a.itemsize)
print(a.ndim)
print(a.dtype)
请注意,您不能正确写入文件,在第一种情况下,一次只能写入一个参数,您需要将它们
str.join
或执行多个text.write
s。在第二种情况下,您应该检查的文档-它期望数组作为第二个参数,而不是多个属性的列表
例如:
with open("demo_numpy.tx","w") as text:
text.write(str(a))
text.write(str(shape))
text.write(str(size))
text.write(str(itemsize))
text.write(str(ndim))
text.write(str(dtype))
# or:
# text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])))
np.savetxt('demo_numpy.txt', a)
我想用这样的东西:
# import numpy as np
# my_array = np.arange(3)
metadata = [(method, getattr(my_array, method)) for method in dir(my_array) if (not callable(getattr(my_array, method))) and (not method.startswith('__'))]
names, values = zip(*metadata) # 2 lists
然后在
名称
和值
上循环并写入文件 你为什么要做a=print(a)
print
返回None
。我添加了“variable=”以便可以在输出文件语句中列出print语句。啊,关于print的功能,您弄错了。姆塞弗特解释了原因。当我尝试你的建议时,我发现两个错误。每个文本函数一个。TypeError:write()不接受关键字参数,TypeError:array dtype('object')和格式说明符('%.18e')之间不匹配最后一段应该解释为什么会发生这种情况。您正在错误地使用文件。写入和np.savetxt
。也就是说,试试np.savetxt('demo\u numpy.txt',a)
。好的,所以我想根据您评论中的第一个代码块访问这些值。但是现在,如何将它们打印到一个txt文件中,每个变量都在一个新行上?好吧,只需文本。一次编写一个并在适当的时候插入新行。:)@MSeifert-仅用于澄清。我需要打印数据类型名称,而不是数据类型。我做得对吗?有什么区别?