如何用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
- Read the file: Open
hisEasyR.txtand loop through each line of data. - Extract scores: Split each line using
|as the separator, grab the second value (the score), and convert it to an integer. - Compute the average: Sum all the collected scores and divide by the number of entries to get the average.
- 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-exceptblock to skip invalid entries (though your existing write code ensures valid integers).
内容的提问来源于stack exchange,提问作者Programmer12
相关产品推荐
相关产品推荐

