Python计算费率最值与均值时,如何保留对应整行信息?
Hey there! Great job getting the basic calculations (average, max, min rates) working—you’re already on solid ground. Let’s tweak your code to keep track of the full row information (company name, state, zip, etc.) when we hit those max and min rates instead of just storing the rate value itself.
Here’s the Updated Code
Instead of storing just the rate number, we’ll store the entire line for the max and min entries. We’ll also avoid using sum as a variable name (it’s a built-in Python function, so overwriting it can cause issues later):
# Initialize variables to hold the full rows for max/min rates max_rate_row = None min_rate_row = None count = 0 sum_rates = 0 # Renamed from 'sum' to avoid overwriting the built-in function with open(file_names, "r") as file_out: next(file_out) # Skip the header line for line in file_out: line = line.strip() # Remove extra newlines/spaces values = line.split(",") current_rate = float(values[6]) # Convert rate to float once per line # Update max rate row: if no row exists yet, or current rate is higher if max_rate_row is None or current_rate > float(max_rate_row.split(",")[6]): max_rate_row = line # Update min rate row: if no row exists yet, or current rate is lower if min_rate_row is None or current_rate < float(min_rate_row.split(",")[6]): min_rate_row = line count += 1 sum_rates += current_rate avg_rate = sum_rates / count # Print results with full details print(f"Average Rate: {avg_rate:.2f}") print("\n--- Max Rate Details ---") print(max_rate_row) print("\n--- Min Rate Details ---") print(min_rate_row)
Key Changes Explained
- Track full rows: We use
max_rate_rowandmin_rate_rowto store the entire line of text instead of just the rate value. This keeps all the associated data intact. - Avoid redundant conversions: We convert the current line’s rate to a float once (
current_rate) instead of doing it multiple times in comparisons. - Safe initialization: Starting with
Nonelets us handle the first line correctly (since there’s no prior max/min to compare against).
Bonus: Format the Output for Readability
If you want to print the details in a more user-friendly way (instead of just the raw comma-separated line), you can split the row back into values and label them:
# Format max rate details max_values = max_rate_row.split(",") print("\n--- Max Rate Details ---") print(f"Company Name: {max_values[0]}") print(f"State: {max_values[1]}") print(f"ZIP Code: {max_values[2]}") print(f"Rate: {float(max_values[6]):.2f}") # Format min rate details min_values = min_rate_row.split(",") print("\n--- Min Rate Details ---") print(f"Company Name: {min_values[0]}") print(f"State: {min_values[1]}") print(f"ZIP Code: {min_values[2]}") print(f"Rate: {float(min_values[6]):.2f}")
Handling Ties (Multiple Rows with Same Max/Min Rate)
If your file has multiple rows with the same maximum or minimum rate, the code above will only keep the last one it encounters. To save all matching rows, use lists instead of single variables:
max_rate_rows = [] min_rate_rows = [] # Inside the loop: if not max_rate_rows: # First row, add it max_rate_rows.append(line) else: current_max = float(max_rate_rows[0].split(",")[6]) if current_rate > current_max: # New higher rate, reset the list max_rate_rows = [line] elif current_rate == current_max: # Same max rate, add to list max_rate_rows.append(line) # Repeat similar logic for min_rate_rows
This way, you’ll have all rows that share the maximum or minimum rate stored in the lists.
内容的提问来源于stack exchange,提问作者Alex

