【问题标题】:Write output of for loop in python在python中编写for循环的输出
【发布时间】:2016-07-19 17:38:25
【问题描述】:

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

【问题讨论】:

  • 您的 for 循环中有一个 print 语句,因此在编写输出时应该可以正常工作。不是在做你想做的事吗?它在做什么,你希望它做什么?
  • 提示:for line in f 而不是用content = f.readlines() 蚕食你的记忆
  • @Kevin 我想将每个输出保存到一个变量中,以便我可以根据需要调用它们中的任何一个以进行进一步的操作

标签: python for-loop output


【解决方案1】:

为什么不把它们保存到一个数组中(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

【讨论】:

    猜你喜欢
    • 2014-08-16
    • 2019-07-20
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    相关资源
    最近更新 更多