Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试在for循环中保存具有不同名称的变量_Python_Save - Fatal编程技术网

Python 尝试在for循环中保存具有不同名称的变量

Python 尝试在for循环中保存具有不同名称的变量,python,save,Python,Save,我试图使用np.savetxt将变量的结果保存在.txt文件中。代码非常简单 for n in range(2000,11000,2000): avdist = [0]*(np.max(idx)+1) #average distance of the vectors belonging to their corresponding cluster avdist1 = [0]*(np.max(idx)+1) for i in range(0, np.max(idx)+1

我试图使用np.savetxt将变量的结果保存在.txt文件中。代码非常简单

for n in range(2000,11000,2000): 
    avdist = [0]*(np.max(idx)+1)  #average distance of the vectors belonging to their corresponding cluster
    avdist1 = [0]*(np.max(idx)+1)
    for i in range(0, np.max(idx)+1):  
        avdist[i] = np.mean([np.linalg.norm(e[x]-centroids[i]) for x in range(len(e)) if idx[x] == i])
        avdist1[i] = np.mean([np.linalg.norm(e[x]-centroids[i]) for x in range(len(e)) if idx[x] != i])
    np.savetxt('avdist{0}.txt'.format(n), avdist)
但我得到了一个索引器:元组索引超出范围

为什么会这样?我希望结果是avdist2000、avdist4000等等

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/npyio.py", line 1034, in savetxt
    ncol = X.shape[1]
IndexError: tuple index out of range
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
savetxt中的文件“/usr/local/ceral/python/2.7.8/Frameworks/python.framework/Versions/2.7/lib/python2.7/site packages/numpy/lib/npyio.py”,第1034行
ncol=X.shape[1]
索引器错误:元组索引超出范围

您需要提供更多的代码(什么是“各种计算”)。
索引器
不是从您提供的代码行引发的。现在检查一下,我编辑了我的帖子谢谢。你能提供你的堆栈跟踪吗?我希望这就是你的意思:)是的,就是这样。痕迹清楚地表明第1行的
ncol=X.shape[1]
是罪魁祸首。您根本没有在问题中包含此代码,因此无法进一步排除故障。但是显然
shape
只包含一个元素(如果是这样的话),因此索引
[1]
超出了范围(您的意思是
[0]
还是它不包含您假设的内容?)