IndexError:元组索引超出范围与写入txt文件
问题描述:
我有我的代码IndexError:元组索引超出范围与写入txt文件
import numpy as np
a1=np.empty(10)
a1.fill(1900)
a2=np.empty(10)
a2.fill(3100)
a3=np.empty(10)
a3.fill(3600)
with open('homes.txt', 'w') as f:
for i in a1:
for j in a2:
for k in a3:
np.savetxt(f, i, j,k)
我想写阵列到文本文件中像这样
1900. 3100. 3600.
1900. 3100. 3600.
1900. 3100. 3600.
但终端给我
Traceback (most recent call last):
File "m84.py", line 16, in <module>
np.savetxt(f, i, j,k)
File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1034, in savetxt
ncol = X.shape[1]
IndexError: tuple index out of range
如果我的想法有误,有人提出其他解决方案会很好。
答
您可以通过编写正常文件做到这一点:
with open('homes.txt', 'w') as f:
for i in a1:
for j in a2:
for k in a3:
f.write("%f %f %f\n"%(i,j,k))
不过,我怀疑你不是真的想这样做正是这一点,因为这将打印1000行(嵌套的,因为循环)。如果你只是想将数组写入一个文件中,一旦你使用了savetxt
就可以写入每个值,并且你不需要把它放在一个循环中。它可以编写一个整个数组一次,所以你可以如下做到这一点:
a = np.empty(shape = (10,3))
a[:,0].fill(1900)
a[:,1].fill(3100)
a[:,2].fill(3600)
np.savetxt("homes.txt",a)
好,它的工作原理,但我得到了在file.How 100线应该I指数排列A1 [I]? – milenko
编辑,它回答你的问题吗? – Cantfindname
是的,谢谢,这是最好的答案。 – milenko