Skip to main content
 首页 » 编程设计

python之索引错误 : tuple index out of range with write to txt file

2025年04月02日18rubylouvre

我有我的代码

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)