【问题标题】:Printing a table of numbers from a file, then averaging each column从文件中打印一个数字表,然后平均每一列
【发布时间】:2020-03-27 17:21:24
【问题描述】:

我正在尝试在 Python 中创建适当的代码。我创建了一个名为“数字”的文本文件,然后让 python 在平均之前列出数字。有 2 列数字,它们是 'float' 格式。

到目前为止,这是我想出的:

def main():

     outfile = open("numbers.txt", 'r')

     numRow = 0.0
     total1 = 0.0
     total2 = 0.0

     for line in outfile:
          col1, col2 = line[:-1].split(" ")
          col1 = eval(col1)
          col2 = eval(col2)
          print(col1, col2)
          print()
          total1 = col1 + 1
          total2 = col2 + 1
          numRow = numRow + 1

     print("Your total for column 1 is:",total1)
     print("Your total for column 2 is:",total2)
     print()
     print("The average of column 1 is:",total1/numRow)
     print("The average of column 2 is:",total2/numRow)

main()

我没有得到正确的总数,显然是平均值。

【问题讨论】:

  • total1 = col1 + 1 将 total1 设置为 col1 的值加 1。您可能不希望这样。
  • 我会将两个总数调整为:'total1 = total1 + col1' 和 'total2 = total2 + col2' 吗?
  • 还可以尝试发布您的文本文件的小样本,以便我们验证解决方案
  • 看起来我犯了一个错误,在两个总数上都使用“+ 1”而不是“+ total1”和“+ total2”。我现在得到正确的总数和平均值。非常感谢@MichaelButscher
  • 我建议你把它分解成更小的部分。尝试编写一个总计单列数字的程序。并打印总数和平均值。

标签: python loops file


【解决方案1】:

试试这样的:

def main():

     outfile = open("numbers.txt", 'r')

     numRow = 0.0
     total1 = 0.0
     total2 = 0.0

     for line in outfile:
          # you can drop the argument to split as that is the default
          col1, col2 = line[:-1].split()
          col1 = eval(col1)
          col2 = eval(col2)
          print(col1, col2)
          print()
          # use the += operator
          total1 += col1
          total2 += col2
          numRow +=  1

     print("Your total for column 1 is:",total1)
     print("Your total for column 2 is:",total2)
     print()
     print("The average of column 1 is:",total1/numRow)
     print("The average of column 2 is:",total2/numRow)

main()

【讨论】:

  • 感谢罗伯特·金!这正是我需要做的。
猜你喜欢
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多