如何在不使用re.split的情况下用Python的.split处理两个分隔符?
How to Split by Multiple Delimiters Without
re.split() and Calculate Student Averages Hey there! I get that you can't use re.split() for your exercise, so let's work through a solution using basic string methods instead. Here's how to tackle extracting student grades, calculating averages, and writing the results:
Step 1: Clean Up the Grade Data
Your current code reads the grades into text2 with split("\n"), but this leaves empty strings from blank lines. First, we'll filter out those empty lines and strip any extra whitespace from each line:
f1 = open("data/namesStudents.txt") f2 = open("data/namesGrades.txt") # Read student names (assuming each name is separated by whitespace) student_names = f1.read().split() # Read grades and clean up lines grade_lines = f2.read().split("\n") # Filter out empty lines and strip leading/trailing whitespace from valid lines clean_grade_lines = [line.strip() for line in grade_lines if line.strip()] # Now process each line to get individual grades student_grades = [] for line in clean_grade_lines: # Split by whitespace (handles multiple spaces automatically) grades = [int(score) for score in line.split()] student_grades.append(grades)
Step 2: Calculate Averages
Next, we'll compute the average for each student. Make sure to pair each name with their corresponding grade list:
student_averages = [] for name, grades in zip(student_names, student_grades): average = sum(grades) / len(grades) # You can format the average to 2 decimal places if needed student_averages.append(f"{name}: {average:.2f}")
Step 3: Write Results to a New File
Finally, write the name-average pairs to a new text file:
with open("data/student_averages.txt", "w") as output_file: output_file.write("\n".join(student_averages)) # Don't forget to close the original files! f1.close() f2.close()
Key Notes:
split()without arguments automatically splits on any whitespace (spaces, tabs, multiple spaces), which handles the space-separated scores perfectly.- Using a list comprehension with
if line.strip()filters out empty lines (sinceline.strip()will be an empty string for blank lines, which evaluates toFalse). - We use
zip()to pair names with their grade lists—just make sure the number of names matches the number of grade entries!
内容的提问来源于stack exchange,提问作者Claudio Albino
相关产品推荐
相关产品推荐

