【问题标题】:Taking the average of integers in a text file (using Python)取文本文件中整数的平均值(使用 Python)
【发布时间】:2018-01-21 15:44:27
【问题描述】:

这是我的代码:

results = [[usernme, score]]

with open("hisEasyR.txt", "a") as hisEasyRFile:
        writer = csv.writer(hisEasyRFile, delimiter='|')
        writer.writerows(results)

这是文本文件的样子:

mary|4
john|5
ben|3

我想取所有整数并计算平均值。 例如,对于这个文件,我希望它输出:

The average is 4. 

我该怎么做呢?

【问题讨论】:

    标签: python python-2.7 int text-files average


    【解决方案1】:

    你可以使用list comprehension:

    with open("hisEasyR.txt") as hisEasyRFile:
        numbers = [int(line.rstrip('\n').split('|')[-1])
                   for line in hisEasyRFile if not line.isspace()]
    
    print "The average is %d." % (sum(numbers) / len(numbers))
    # The average is 4.
    

    【讨论】:

    • 嗨,对不起,我绝对不是 Python 专家。我很不擅长纠正程序哈哈。我收到错误 print "The average is %d." % (sum(ls) / len(ls)) NameError: global name 'ls' is not defined
    • @Programmer12,抱歉打错了。将其更改为numbers。现在它应该可以工作了。
    • 完美!!谢谢!如果我愿意,如何将平均值更改为浮点数?我试图将numbers = [int(line.rstrip('\n').split('|')[-1]) 中的“int”更改为float,但没有任何影响:)
    • int(line.rstrip('\n').split('|')[-1]) 更改为float(line.rstrip('\n').split('|')[-1])
    • 并在print 语句中,将%d 更改为%f
    【解决方案2】:

    漫长的道路: 逐行阅读,在 | 上使用字符串拆分。 然后取第二个字符串(即数字),并将其转换为 int。

    参考:https://www.tutorialspoint.com/python/string_split.htm

    伪:

    sum = 0
    
    For line in file:
         mySplit = str.split(line, '|')
         sum += int(mySplit[1])
    
    avg = sum/numLines
    

    【讨论】:

      【解决方案3】:

      两行:(假设您已经将整个文件读到content

      new_list = [int(i.split("|")[1]) for i in content.split("\n") if "|" in i]
      print "The average is " + str(sum(new_list) / float(len(new_list)))
      

      【讨论】:

      • 我对 Python 还很陌生哈哈。你能给我一个如何将文件读入内容的例子吗?
      • 简而言之:with open('Path/to/file', 'r') as file: content = file.read() 看看这里:stackoverflow.com/questions/7409780/…
      • 谢谢!我收到错误 IndexError: list index out of range
      • new_list = [int(i.split("|")[1]) for i in content.split("\n")] IndexError: list index out of range
      • 您的意见是什么?我想问题出在空行上。我更新了我的答案
      猜你喜欢
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多