【问题标题】:Converting text file to list then finding items with in a list, how to fix my code?将文本文件转换为列表,然后在列表中查找项目,如何修复我的代码?
【发布时间】:2017-04-05 10:03:22
【问题描述】:

所以我正在做一个项目,但我正在为此苦苦挣扎。 然后我需要将文本文件转换为列表:

  • 使用 LIST FUNCTION(S) 找到最小值

  • 使用 LIST FUNCTION(S) 查找最大值

  • 查找使用 LIST FUNCTION(S) 读取的值的数量

  • 读取值的平均值。
  • 列表的中值
  • 列表中出现频率最高的值,以及出现的次数。
  • 从文件中读取的值,没有重复,按降序排列。

    try: 
        listFile = open('input.txt','r')
        line = listFile.readline()
        listFile.write(line)
        read += 1 
        total += line
        listFile.sort()
    
        smallest = min in line
        largest = max in line
        average = (total/read)
    
        import listFile
        middle = listFile.median
    
        outputInfo = open('output.txt','w')
        outputInfo.write('The smallest value is:',smallest)
        outputInfo.write('The largest value is:',largest)
        outputInfo.write('The number of values read is:',read)
        outputInfo.write('The median of the values read is',middle)
    
        close('input.txt')
    
    except IOError: 
        print('The file could not be found/read')
    except ValueError: 
        print('This value is not accepted')
    except: 
        print('An error occured while trying to run the program')
    

【问题讨论】:

  • 文件格式是什么?
  • 它是一个 python 文件,但它打开并写入一个文本文件
  • 不是文件,数组是怎么表示的? 1 2 3 4 51, 2, 3, 4, 51-2-3-4-5?
  • 这个文件没有已知值或任何东西,它只是读取文件并找到所有内容

标签: python list exception try-catch median


【解决方案1】:

考虑到你有一个数组arr

smallest = min(arr)
largest = max(arr)
sum_of_array = sum(arr)
number_of_elements = len(arr)

import statistics
average = statistics.mean(arr)
median= statistics.median(arr)

关于该文件,尚不清楚这些值是如何保存的。我假设一个以空格分隔的列表文件,保存在 data.txt 中,就像

2 5 34 78 2 89 345 6 54 7 667 87 34

然后创建数组会像

arr = sorted([int(x) for x in open('data.txt').read().split()])

【讨论】:

  • 如何用数组做中位数?
  • 我还需要排序吗?
  • 当我跑步或尝试时它也会告诉我这个
  • /usr/bin/python: 在 '' 中找不到 'main' 模块
  • 那么我会将它放在我的文件中的什么位置?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
  • 2023-02-01
相关资源
最近更新 更多