在python中写入for循环的输出

时间:2016-07-19 17:38:25

标签: python for-loop output

我正在尝试编写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。 有关如何进行的任何建议吗?

1 个答案:

答案 0 :(得分: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