【发布时间】: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
-
我建议你把它分解成更小的部分。尝试编写一个总计单列数字的程序。并打印总数和平均值。