首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python3二维阵列

Python3二维阵列
EN

Stack Overflow用户
提问于 2020-03-23 10:16:31
回答 1查看 98关注 0票数 0

我想使用重定向操作符<打印标准输入文件中2行的行平均值。输入将是[99.0,85.0,98.0,98.0,57.0,79.0]平均值应打印在最后一列的右侧。有没有人能帮我弄明白我做错了什么?我会很感激的!当我运行它时,它给我一个错误“浮动对象不可订阅”。

代码语言:javascript
运行
复制
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) + ' ')
EN

回答 1

Stack Overflow用户

发布于 2020-03-23 11:00:03

假设您的grades.txt文件如下所示:

代码语言:javascript
运行
复制
99.0 85.0 98.0
98.0 57.0 79.0

尝试以下代码:

代码语言:javascript
运行
复制
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)

像这样运行:

代码语言:javascript
运行
复制
python3 test.py < grades.txt

结果:

代码语言:javascript
运行
复制
[[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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60807162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档