2016-07-19 152 views
-1

我正在嘗試爲for循環寫入每個迭代輸出以進一步操作。 這是我的代碼在python中寫for循環的輸出

#!/usr/bin/python 

import io 
from operator import itemgetter 
with open('test.in') as f: 
    content = f.readlines() 
    content = [int(x) for x in content] 
    content = tuple(content) 
    nClus = input("Number of Clusters: ") 
    nEig = input("Number of eigen values: ") 
    j = 0 
    k = nClus + 1 
    content1 = "" 
    for i in range(1,k): 
     print content[j*(nEig+1):i*(nEig+1)] 
     j = j + 1 

文件test.in看起來像這樣(這是一個例子,實際test.in包含數據的巨大的量)

40 
1 
4 
3 
5 
7 
29 
6 
9 
4 
7 
3 
50 
1 
2 
3 
4 
5 
57 
9 
8 
7 
6 
5 

值nClus = 4,nEig = 5. 關於如何進行的任何建議?

+0

你在for循環中有一個'print'語句,所以在寫入輸出時應該做得很好。它不是在做你想要的嗎?它在做什麼,你想要做什麼? – Kevin

+0

提示:'用於f行',而不是用'content = f.readlines()'帶走你的記憶'' –

+0

@Kevin我想​​將每個輸出保存到一個變量中,以便我可以根據需要調用其中的任何一個我的進一步行動 – ratamboli

回答

0

爲什麼不把它們保存到一個數組(下面的mydata)?我沒有看到j停止的位置(other_dimension,如果您只有一維結果,我不知道您的數組大小,您可能只需將其刪除),但您可以按照此格式獲取一個numpy數組來保存數據到:

import numpy as np 
... [your code] 
    mydata = np.zeros([k,other_dimension]) // other_dimension only if you are saving a rectangular matrix of results instead of a vector 
    for i in range(1,k): 
     mydata[row, column] = content[j*(nEig+1):i*(nEig+1)] // put your iterators here for row, column if applicable (rectangular matrix), otherwise mydata[iterator] 
     print mydata[k, other_dimension] // other_dimension only if you are saving a rectangular matrix of results instead of a vector 
     j = j + 1