简体   繁体   English

IndexError:元组索引超出范围,写入 txt 文件

[英]IndexError: tuple index out of range with write to txt file

I have my code我有我的代码

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)

I want to write arrays to text file like this我想像这样将数组写入文本文件

1900. 3100. 3600. 
1900. 3100. 3600. 
1900. 3100. 3600. 

But terminal gives me但是终端给了我

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

If my idea is wrong it would be nice that someone proposes other solution.如果我的想法是错误的,那么有人提出其他解决方案会很好。

You can do this by writing to the file normally:您可以通过正常写入文件来执行此操作:

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))

However, I am suspecting that you don't really want to do exactly this, because this will print 1000 lines (because of the nested loops).但是,我怀疑您真的不想这样做,因为这将打印 1000 行(因为嵌套循环)。 If you just want to write the arrays in a file, with each value being written once you can use savetxt , and you don't need to place it inside a loop.如果您只想在文件中写入数组,则可以使用savetxt每个值写入一次,并且不需要将其放入循环中。 It can write a whole array at once, so you could do it as follows:它可以一次写入整个数组,因此您可以按如下方式执行:

a = np.empty(shape = (10,3))
a[:,0].fill(1900)
a[:,1].fill(3100)
a[:,2].fill(3600)
np.savetxt("homes.txt",a)

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

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