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

使用Python处理CSV文件:查找指定性别下最接近输入值的分数

Find Closest Test Score by Gender in Python

Nice start with your code—you’ve already nailed filtering scores by gender, which is a great first step! Let’s build on that logic to find the score(s) closest to the user’s input, including handling cases where multiple students might have the same closest score.

Step-by-Step Improvements:

  • Convert user input to a numeric type: Your user_score is currently a string, so we’ll convert it to an integer to do mathematical comparisons.
  • Track closest records: We’ll use variables to keep tabs on the smallest score difference we’ve found, plus the student details that match that difference.
  • Compare differences: For each matching gender entry, calculate the absolute difference between the student’s score and the user’s input. Update our tracking variables when we find a closer score, or add to the list if there’s a tie.

Updated Full Code:

import csv

user_gender = input("Male or Female\n")
# Handle non-numeric score input to avoid crashes
try:
    user_score = int(input("Closest test score\n"))
except ValueError:
    print("Please enter a valid number for the score!")
    exit()

path = r'C:\Users\Joe\Desktop\Exercise\test_score.csv'

# Initialize tracking variables
min_diff = float('inf')  # Start with a very large "worst case" difference
closest_records = []

with open(path, 'r') as csvfile:
    readCSV = csv.DictReader(csvfile, delimiter=',')
    for line in readCSV:
        gender = line['Gender']
        if user_gender.lower() == gender.lower():
            score = int(line['Score'])
            # Calculate absolute difference (ignores if score is higher/lower)
            current_diff = abs(score - user_score)
            
            # Update closest records if this is a better match
            if current_diff < min_diff:
                min_diff = current_diff
                closest_records = [line]  # Reset list with this new closest entry
            elif current_diff == min_diff:
                closest_records.append(line)  # Add to list if there's a tie

# Display results
if closest_records:
    print(f"\nClosest score(s) to {user_score} for {user_gender.title()}:")
    for record in closest_records:
        print(f"- {record['First Name']} {record['Last Name']}: {record['Score']}")
else:
    print(f"No records found for gender: {user_gender}")

Key Details:

  • try/except block: Prevents crashes if the user enters a non-number for the score, with a friendly error message.
  • float('inf'): A clean way to start with a difference that any real score will be smaller than.
  • Absolute difference: Using abs() ensures we’re looking for the closest score regardless of whether it’s higher or lower than the user’s input.
  • Tie handling: If multiple students have the same closest score, all their records are saved and displayed.

Example Output:

If the user enters Female and 85, the output will be:

  • Jennifer Bradley: 80
  • Jane Doe: 97

Both scores are exactly 5 points away from 85, so they’re both included.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:10:59