gpt4 book ai didi

python - 将 numpy 数组的内容和几个属性打印到文本文件

转载 作者:行者123 更新时间:2023-11-28 18:20:56 24 4
gpt4 key购买 nike

我有一个数组。我的任务是打印出数组及其形状、大小、项目大小、维度和数据类型名称。输出应该是一个文本文件——每个属性都应该在一个新行上。

当我尝试使用以下代码时,出现错误:

  File "<ipython-input-76-f4d4f45285be>", line 1, in <module>
print(a.shape)

AttributeError: 'NoneType' object has no attribute 'shape'

我尝试了两个选项,打开一个文本文件和np.savetxt。两者似乎都不起作用。

代码如下:

import numpy as np

a = np.arange(15).reshape(3,5)

a = print(a)

shape = print(a.shape)

size = print(a.size)

itemsize = print(a.itemsize)

ndim = print(a.ndim)

dtype = print(type(a.dtype))

with open("demo_numpy.tx","w") as text:
text.write(a,shape,size,itemsize,ndim,dtype, file = text)

np.savetxt('demo_numpy.txt',[a,shape,size,itemsize,ndim,dtype])

我做错了什么,我该如何修正我的输出?

最佳答案

print 只是打印传递给stdout 的值 返回None。如果你想访问一个属性,不用 print 就可以了:

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,不要分配print的返回值:

print(a)
print(a.shape)
print(a.size)
print(a.itemsize)
print(a.ndim)
print(a.dtype)

请注意,您没有正确地写入文件,在第一种情况下,您一次只能写入一个参数,您需要 str.join 它们或执行多个 text .writes。在第二种情况下,您应该查看 numpy.savetxt 的文档- 它需要一个数组作为第二个参数,而不是几个属性的列表。

例如:

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)

关于python - 将 numpy 数组的内容和几个属性打印到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45119400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com