我想使用重定向操作符<打印标准输入文件中2行的行平均值。输入将是[99.0,85.0,98.0,98.0,57.0,79.0]平均值应打印在最后一列的右侧。有没有人能帮我弄明白我做错了什么?我会很感激的!当我运行它时,它给我一个错误“浮动对象不可订阅”。
import stdio
import stdarray
m = 2
n = 3
a = stdarray.create2D(m, n + 1, 0.0)
While not stdio.isEmpty():
a = stdio.readFloat()
for i in range(m):
total = 0.0
for j in range(n):
total += a[i][j]
a[i][4] = total / m
stdio.writeln(str(a) + ' ')
发布于 2020-03-23 11:00:03
假设您的grades.txt文件如下所示:
99.0 85.0 98.0
98.0 57.0 79.0
尝试以下代码:
import stdio
import stdarray
import sys
m = 2
n = 3
a = stdarray.create2D(m, n + 1, 0.0)
row = 0
column = 0
total = 0.0
while not stdio.isEmpty():
# read each float and store in input_text
input_text = stdio.readFloat()
# store the float in 0,0 first
a[row][column] = input_text
# before reading the next one, increment column
# and add to the total
column += 1
total += input_text
# if your column is now 3, it is time to switch to the next row
# add total to the last column in the row
# reset the total, reset the column and increment the row
if column == n:
a[row][column] = total/n
total = 0
column = 0
row += 1
print(a)
像这样运行:
python3 test.py < grades.txt
结果:
[[99.0, 85.0, 98.0, 94.0], [98.0, 57.0, 79.0, 78.0]]
stdio.py为https://introcs.cs.princeton.edu/python/code/stdio.py
stdarray.py为https://introcs.cs.princeton.edu/python/code/stdarray.py
https://stackoverflow.com/questions/60807162
复制相似问题