【问题标题】:Calculate averages of stdin in python在python中计算标准输入的平均值
【发布时间】:2021-02-15 09:30:42
【问题描述】:

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

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

现在我想计算每组的平均值。 我知道我可以从标准输入读取

for line in sys.stdin:

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

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

但是如何在 Python3 中读取每组的成绩并计算它的数量?

【问题讨论】:

  • 你能举一个可重现的例子吗?你的数据是什么格式的?一个df?一个列表? ETC。? @PdH
  • 谁对所有建议的答案投了反对票,为什么!请给出原因并发表您自己的答案。
  • @CiaranOBrien 到目前为止,没有一个答案真正回答了这个问题。一个人不读输入。一个不会平均所有组。由于所有 NameErrors,一个在我的 IDE 中像圣诞树一样亮起。
  • @PdH 数据实际上是按组排序的,还是1gT 也可能出现在1gZ 之后? (Group),(Grade): 是输入的一部分吗?您只是想打印结果,或者说,将其存储在从组名到平均值的字典中?
  • @CiaranOBrien 正如问题所说“我想从标准输入读取python,它看起来像这样:”。那是一个列表,是的,但不是list。

标签: python average stdin


【解决方案1】:

感谢大家的思考。 感谢 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)

【讨论】:

    【解决方案2】:
    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()
    

    这是一个粗略的现成示例。

    【讨论】:

    • 这不读取标准输入。它已经假定数据被正确读取。
    猜你喜欢
    • 2014-03-21
    • 2017-01-18
    • 2018-06-17
    • 1970-01-01
    • 2021-04-30
    • 2011-12-04
    • 2012-04-20
    相关资源
    最近更新 更多