【问题标题】:Reading a file then converting the string into a float and finding avg,sum,lowest,and highest totals读取文件,然后将字符串转换为浮点数并找到平均、总和、最低和最高总数
【发布时间】:2019-04-11 19:36:22
【问题描述】:

我遇到的问题是,当程序读取文件时,它正在读取名称以及必要的数字,但我无法将数字转换为浮点数。文本文件称为“gym.txt”,这就是我必须阅读的内容。我在一个低级编码类,所以代码应该有点基本。以下是“gym.txt”的内容:

5
Albert 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8
John 9.1 9.4 9.6 9.8 9.4 9.3 9.9 9.1
Jay 9.2 9.3 9.0 9.9 9.4 9.3 9.9 9.1
Henry 9.4 9.3 9.9 9.1 9.5 9.5 9.6 9.8
Walter 9.2 9.3 9.4 9.3 9.9 9.1 9.6 9.0

5 表示参赛者的数量,在这些分数中,每个人的最高和最低被丢弃。然后总数变为 6,并且不包括每个人的最低和最高分数。

我已尝试逐行读取文件,如下面的代码所示,但由于名称与数字在同一行,将其转换为浮点数失败。如果可行,我计划为每个名称和分数集执行此代码。

f=open('gym.txt','r')
judges=6
contestants=f.readline().rstrip("\n")
print(contestants)
albert=str(f.readline().rstrip('\n'))
albert_list=float(albert.strip("Albert"))
print(albert_list)

预期的结果是以下输出:

The number of contestants is 5.

Contestant          Scores
_______________________________________________

Albert  9.3 9.0 9.9 9.5 9.5 9.6 9.8 

John    9.4 9.6 9.8 9.4 9.3 9.9 9.1 

Jay 9.3 9.0 9.9 9.4 9.3 9.9 9.1 

Henry   9.3 9.9 9.1 9.5 9.5 9.6 9.8 

Walter  9.3 9.4 9.3 9.9 9.1 9.6 9.0 
Total score of Albert is 9.48.
Total score of John is 9.43.
Total score of Jay is 9.37.
Total score of Henry is 9.52.
Total score of Walter is 9.32.
The highest total score amongst the contestants is 9.52.
The lowest total score amongst the contestants is 9.32.

格式化对我来说不是一个大问题,我只是对程序本身的帮助感兴趣。这是我得到的错误:

5
Traceback (most recent call last):
  File "C:/Users/theon/PycharmProjects/untitled/CS 1113/gymnasium.py", line 6, in <module>
    albert_list=float(albert.strip("Albert"))
ValueError: could not convert string to float: ' 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8'

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    你可以这样做:

    with open('gym.txt', 'r') as file:
        all_file = file.read().strip()  # Read and remove any extra new line
        all_file_list = all_file.split('\n')  # make a list of lines
        number_of_contestant = all_file_list.pop(0)  # get the first line (removes form the all_file_list as well)
        data = []
        # Except for names, number will be converted to floats, Rejects the 1st max and min number too
        for line in all_file_list:
            line_list = line.split()
            temp_list = [x if i == 0 else float(x) for i, x in enumerate(line_list)]  # convert string float to Float
            temp_list.remove(max(temp_list[1:]))  # Remove the max
            temp_list.remove(min(temp_list[1:]))  # Remove the min
            data.append(temp_list)
        print('The number of contestants is {}.'.format(number_of_contestant))
        print('_' * 50)
        print('{} {:^50}'.format('Contestent', 'Scores'))
        print('_' * 50)
        for row in data:
            print('{:<15} {}'.format(row[0], '  '.join([str(x) for x in row[1:]])))
        print('_' * 50)
        print('_' * 50 + '\n')
        total_score = []
        for row in data:
            row_total_score = sum(row[1:]) / len(row[1:])
            total_score.append(row_total_score)
            print('{:<30} {:.2f}'.format('Total Score of ' + row[0] + ' is: ', row_total_score))
        print('_' * 50 + '\n' + '_' * 50 + '\n')
        print('The highest total score amongst the contestants is {:.2f}'.format(max(total_score)))
        print('The lowest total score amongst the contestants is {:.2f}'.format(min(total_score)))
    

    输出:

    The number of contestants is 5.
    __________________________________________________
    Contestent                       Scores
    __________________________________________________
    Albert          9.2  9.3  9.5  9.5  9.6  9.8
    John            9.4  9.6  9.8  9.4  9.3  9.1
    Jay             9.2  9.3  9.4  9.3  9.9  9.1
    Henry           9.4  9.3  9.5  9.5  9.6  9.8
    Walter          9.2  9.3  9.4  9.3  9.1  9.6
    __________________________________________________
    __________________________________________________
    
    Total Score of Albert is:      9.48
    Total Score of John is:        9.43
    Total Score of Jay is:         9.37
    Total Score of Henry is:       9.52
    Total Score of Walter is:      9.32
    __________________________________________________
    __________________________________________________
    
    The highest total score amongst the contestants is 9.52
    The lowest total score amongst the contestants is 9.32
    

    参考资料:

    1. 格式
    2. 列表理解
    3. 最小,最大

    【讨论】:

      【解决方案2】:

      使用 pandas 可以这样做

      import pandas as pd
      import numpy as np
      
      df=pd.read_csv('gym.txt', sep=' ', header=None).set_index(0)
      df=df.where(df.values != df.min(axis=1)[:,None])
      df=df.where(df.values != df.max(axis=1)[:,None])
      df['mean'] = df.mean(axis=1)
      print('Contestant             Scores')
      print('----------------------------------------')
      print(df.to_string())
      print('----------------------------------------')
      print('''The highest total score amongst the contestants is {:.2f} achieved by {}
      The lowest total score amongst the contestants is {:.2f} achieved by {}'''\
      .format(max(df['mean']),np.argmax(df['mean']),min(df['mean']),np.argmin(df['mean'])))
      
      Out:'''
      Contestant             Scores
      ----------------------------------------
                1    2    3    4    5    6    7    8      mean
      0                                                       
      Albert  9.2  9.3  NaN  NaN  9.5  9.5  9.6  9.8  9.483333
      John    NaN  9.4  9.6  9.8  9.4  9.3  NaN  NaN  9.500000
      Jay     9.2  9.3  NaN  NaN  9.4  9.3  NaN  9.1  9.260000
      Henry   9.4  9.3  NaN  NaN  9.5  9.5  9.6  9.8  9.516667
      Walter  9.2  9.3  9.4  9.3  NaN  9.1  9.6  NaN  9.316667
      ----------------------------------------
      The highest total score amongst the contestants is 9.52 achieved by Henry
      The lowest total score amongst the contestants is 9.26 achieved by Jay'''
      

      【讨论】:

      • 如果你不想显示 NaN 也可以,但我想显示 min 和 max 下降的位置。
      猜你喜欢
      • 2016-11-23
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      相关资源
      最近更新 更多