Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 读取一个文件,然后将字符串转换为浮点数,并查找平均值、总和、最低值和最高值_Python 3.x - Fatal编程技术网

Python 3.x 读取一个文件,然后将字符串转换为浮点数,并查找平均值、总和、最低值和最高值

Python 3.x 读取一个文件,然后将字符串转换为浮点数,并查找平均值、总和、最低值和最高值,python-3.x,Python 3.x,我遇到的问题是,当程序读取文件时,它正在读取名称以及必要的数字,但我无法将数字转换为浮点。文本文件名为“gym.txt”,这就是我必须阅读的内容。我在一个低水平的编码类,所以代码应该是一些基本的。以下是“gym.txt”的内容: 5表示参赛者的数量,在这些分数中,每个人的最高和最低分数都会下降。然后总数变为6,不包括每个人的最低和最高分数 我已经试着逐行读取文件,如下面的代码所示,但将其转换为float失败,因为名称与数字在同一行中。我计划为每个名字和分数集编写这段代码,如果行得通的话 f=op

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

5表示参赛者的数量,在这些分数中,每个人的最高和最低分数都会下降。然后总数变为6,不包括每个人的最低和最高分数

我已经试着逐行读取文件,如下面的代码所示,但将其转换为float失败,因为名称与数字在同一行中。我计划为每个名字和分数集编写这段代码,如果行得通的话

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'
5
回溯(最近一次呼叫最后一次):
文件“C:/Users/theon/PycharmProjects/untitled/CS 1113/glymasum.py”,第6行,在
albert_list=浮动(albert.strip(“albert”))
ValueError:无法将字符串转换为浮点:“9.2 9.3 9.0 9.9 9 9.5 9.5 9.6 9.8”

您可以这样做:

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

参考资料:

  • 格式
  • 列表理解
  • 最小值,最大值

  • 有了熊猫,可以这样做

    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的位置。
    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'''