You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python计算以|分隔的文本文件中整数的平均值?

Calculate Average Score from hisEasyR.txt

Here's a straightforward, easy-to-follow way to extract the scores from your text file, compute their average, and output the result exactly as you need:

Step-by-Step Breakdown

  1. Read the file: Open hisEasyR.txt and loop through each line of data.
  2. Extract scores: Split each line using | as the separator, grab the second value (the score), and convert it to an integer.
  3. Compute the average: Sum all the collected scores and divide by the number of entries to get the average.
  4. Output the result: Print the average in your desired format, handling edge cases like an empty file.

Complete Code

# Create an empty list to store all the scores
scores = []

# Open the file in read mode (automatically closes after processing)
with open("hisEasyR.txt", "r") as hisEasyRFile:
    # Go through each line in the file
    for line in hisEasyRFile:
        # Remove extra whitespace (like newlines) and split the line into parts
        user_data = line.strip().split("|")
        # Convert the score string to an integer and add it to our list
        score = int(user_data[1])
        scores.append(score)

# Calculate and print the average (handle empty file to avoid errors)
if scores:
    average_score = sum(scores) / len(scores)
    # Since your example expects an integer output, we cast to int here
    print(f"The average is {int(average_score)}")
else:
    print("No scores found in the file.")

Testing with Your Sample Data

If your hisEasyR.txt contains:

mary|4
john|5
ben|3

Running the code will output:

The average is 4

Quick Notes

  • The code includes a check for empty files to prevent a division-by-zero error if there are no scores to average.
  • If you ever need to handle non-integer values or malformed lines, you could add a try-except block to skip invalid entries (though your existing write code ensures valid integers).

内容的提问来源于stack exchange,提问作者Programmer12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:36:28