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

2024-09-30 20:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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

Tags: 文件ofintxtnormfornprange