【问题标题】:Python- Writing all results from a loop to a variablePython-将循环中的所有结果写入变量
【发布时间】:2017-06-11 06:43:33
【问题描述】:

我有一个包含数十列和数百行的.txt 文件。我想将两个特定列的全部结果写入两个变量。我对 for 循环没有很多经验,但这是我尝试循环文件的尝试。

a = open('file.txt', 'r') #<--This puts the file in read mode

header = a.readline() #<-- This skips the strings in the 0th row indicating the labels of each column

for line in a:
    line = line.strip() #removes '\n' characters in text file
    columns = line.split() #Splits the white space between columns
    x = float(columns[0]) # the 1st column of interest  
    y = float(columns[1]) # the 2nd column of interest
    print(x, y)
f.close()

在循环之外,打印xy 只显示文本文件的最后一个值。我希望它具有文件指定列的所有值。我知道 append 命令,但我不确定如何在这种情况下在 for 循环中应用它。

有没有人对如何做到这一点有任何建议或更简单的方法?

【问题讨论】:

    标签: python-2.7 for-loop append text-files


    【解决方案1】:

    您的代码只绑定最后一个元素的值。我不确定这是您的全部代码,但如果您想继续添加列的值,我建议将其附加到数组中,然后在循环之外打印。

    listx = []
    listy = []
    a = open('openfile', 'r')
    #skip the header
    for line in a:
        #split the line
        #set the x and y variables.
        listx.append(x)
        listy.append(y) 
    #print outside of loop.
    

    【讨论】:

      【解决方案2】:

      在开始循环之前创建两个列表 xy 并将它们附加到循环中:

      a = open('file.txt', 'r') #<--This puts the file in read mode
      
      header = a.readline() #<-- This skips the strings in the 0th row indicating the labels of each column
      
      x = []
      y = []
      for line in a:
          line = line.strip() #removes '\n' characters in text file
          columns = line.split() #Splits the white space between columns
          x.append(float(columns[0])) # the 1st column of interest  
          y.append(float(columns[1])) # the 2nd column of interest
      
      f.close()
      
      print('all x:')
      print(x)
      print('all y:')
      print(y)
      

      【讨论】:

      • 太棒了!我没想到这么简单。非常感谢@MikeMüller!这正是我想要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      相关资源
      最近更新 更多