Python列表推导式优化差值范围计数脚本问题求助
Let's break down the issues with your script and get it working as expected, plus simplify it using list comprehensions like you wanted.
First: The Root Causes of Your Counting Error
Your actual output shows unexpected counts (5 for the upper ranges) because of two key issues:
You're overwriting your input file
When you openresult.txtwithwmode for writing, it erases the original content immediately. While this doesn't directly cause the count mismatch, it's a critical mistake—you'll lose your source data! Always write to a different file (likecount_results.txt) instead.Unaccounted values & possible reversed difference
Your script doesn't handle values wherec < 0orc >= 10000—these fall through all yourif/elifblocks and don't get counted anywhere. But the bigger issue is likely that you calculated the difference backwards: if your expected output assumesc = b - a(localDist minus orsDist) instead ofa - b, that would explain why your counts are off.
Fixed & Simplified Script (Using Dictionary for Clarity)
First, let's rewrite the script to be more maintainable and fix the counting issues:
# Define your intervals clearly in a dictionary interval_defs = { "0-10": (0, 10), "10-100": (10, 100), "100-500": (100, 500), "500-1000": (500, 1000), "1000-2000": (1000, 2000), "2000-5000": (2000, 5000), "5000-10000": (5000, 10000) } # Initialize all counters to 0 counts = {name: 0 for name in interval_defs} # Read input data (don't overwrite the original file!) with open("result.txt", "rt") as f_in: for line in f_in: # Strip whitespace/newlines and split the values ors_dist_str, local_dist_str = line.strip().split("-") # Convert to integers safely ors_dist = int(float(ors_dist_str)) local_dist = int(float(local_dist_str)) # Calculate difference - CHECK THIS DIRECTION! # If expected counts are wrong, try reversing this to local_dist - ors_dist diff = ors_dist - local_dist # Match the diff to its interval for interval_name, (low, high) in interval_defs.items(): if low <= diff < high: counts[interval_name] += 1 break # Stop checking once we find the right interval # Write results to a NEW file to preserve input data with open("count_results.txt", "w") as f_out: for interval_name, count in counts.items(): f_out.write(f'in range {interval_name} - {count}\n')
Simplified Version with List Comprehensions
If you want to use list comprehensions to streamline the code, here's a clean approach:
# Step 1: Extract all differences from the input file with open("result.txt", "rt") as f_in: # Use a list comprehension to get all diffs in one go diffs = [ int(float(ors)) - int(float(local)) for line in f_in # Wrap split in a list to unpack safely for ors, local in [line.strip().split("-")] ] # Step 2: Define intervals as a list of tuples intervals = [ ("0-10", 0, 10), ("10-100", 10, 100), ("100-500", 100, 500), ("500-1000", 500, 1000), ("1000-2000", 1000, 2000), ("2000-5000", 2000, 5000), ("5000-10000", 5000, 10000) ] # Step 3: Count values per interval with list comprehensions count_results = [ (name, sum(1 for d in diffs if low <= d < high)) for name, low, high in intervals ] # Step 4: Write the output with open("count_results.txt", "w") as f_out: for name, count in count_results: f_out.write(f'in range {name} - {count}\n')
Key Fixes to Note
- File safety: We write to
count_results.txtinstead of overwritingresult.txt, so you don't lose your original data. - Whitespace handling:
line.strip()removes newline characters and extra spaces, preventing errors when splitting values. - Flexible intervals: Using dictionaries/lists for intervals makes it easy to add/remove ranges without rewriting tons of
if/elifblocks. - Difference direction: Double-check if you need
local_dist - ors_distinstead ofors_dist - local_dist—this is almost certainly why your counts don't match expectations.
内容的提问来源于stack exchange,提问作者Lotarc

