计算 python 中标准输入的平均值

Calculate averages of stdin in python

我想从标准输入中读入 python,它看起来像这样:

(Group),(Grade):
1gT,8
1gT,5
1gT,9
1gT,8
1gX,4
1gX,4
1gX,7
1gZ,2
1gZ,9
1gZ,10

现在我想计算每组的平均值。 我知道我可以使用

从 stdin 读取
for line in sys.stdin:

而且我知道如何计算平均值:

([Sum of all grades from one group] / [number of grades of one group])

但是我怎样才能读取每组的成绩并计算它在 Python3 中的数量?

import pandas as pd

test = ['1gT',8,

'1gT',5,

'1gT',9,

'1gT',8,

'1gX',4,

'1gX',4,

'1gX',7,

'1gZ',2,

'1gZ',9,

'1gZ',10]

# turn list into dataframe
df = pd.DataFrame(test) 

# rename column
df = df.rename({0: 'Group'}, axis=1)  

# break out columns using even numbers and odd numbers
df = pd.DataFrame({'Group':df['Group'].iloc[::2].values, 'Value':df['Group'].iloc[1::2].values})

# Change value to int
df['Value'] = df['Value'].apply(pd.to_numeric) 

# group and get results
grouped_df = df.groupby("Group")
mean_df = grouped_df.mean()

这是一个粗略的例子。

谢谢大家的思考。 感谢 Watanabe.N 的帮助,对您的答案进行了一些修改后它奏效了。

这对我有用:

import sys

ave = 0
total = 0
count = 0
firstline = sys.stdin.readline()
group, grade = firstline.split()
currentGroup = group
grade = int(grade)
total += grade
count += 1

for line in sys.stdin:
    group, grade = line.split()
    grade = int(grade)
    if currentGroup != group:
        print(currentGroup, ave)
        count = 1
        total = 0 + grade
        currentGroup = group
        continue
    count += 1
    total += grade
    ave = total/count
else:
    print(currentGroup, ave)