如何使用数组对城市人口数据进行分组整理并输出至文本文件?
Hey there, sounds like you're halfway there with the sorted population data—let's get that grouping sorted out too. The core challenge here is separating entries with no population data first, then slotting the rest into your specified ranges. I'll walk through this with a Python example (super common for data processing tasks), but the logic translates easily to other languages if that's what you're using.
First, let's recap your existing progress: you already have code that sorts population data from largest to smallest, but it doesn't handle the NA group or categorize the numeric values into the required buckets. Here's how to extend that:
Step 1: Clarify Group Logic
Let's lock down exactly how to assign each city to a group:
- NA: No Population Data: Entries where population is
None, empty string, or non-numeric text - 5000-7499: Population ≥ 5000 and < 7500
- 7500-9999: Population ≥ 7500 and < 10000
- 10000 and Above: Population ≥ 10000
Step 2: Extend Your Code with Grouping
Let's start with a simplified version of your existing sorted code, then add the grouping functionality:
Example Existing Sorted Code
def sort_population(data): # Assumes data is a list of tuples: (city_name, population) # Sorts descending, pushes NA entries to the end sorted_data = sorted( data, key=lambda x: x[1] if x[1] is not None and (isinstance(x[1], int) or x[1].strip()) else -1, reverse=True ) return sorted_data
Updated Code with Grouping
def group_population_data(sorted_data): # Initialize empty groups with your required labels groups = { "NA: No Population Data": [], "5000-7499": [], "7500-9999": [], "10000 and Above": [] } for city, pop in sorted_data: # Handle NA cases first if pop is None or (isinstance(pop, str) and not pop.strip()): groups["NA: No Population Data"].append((city, pop)) else: # Convert string-based population values to integers safely try: population = int(pop) # Assign to the correct range bucket if population >= 10000: groups["10000 and Above"].append((city, population)) elif 7500 <= population < 10000: groups["7500-9999"].append((city, population)) elif 5000 <= population < 7500: groups["5000-7499"].append((city, population)) # Optional: Add a "Below 5000" group if you need it later # else: # groups["Below 5000"].append((city, population)) except ValueError: # If population can't be converted to an integer, treat it as NA groups["NA: No Population Data"].append((city, pop)) # Keep numeric groups sorted descending (matches your original logic) # Sort NA group alphabetically by city for readability for group_name in groups: if group_name != "NA: No Population Data": groups[group_name].sort(key=lambda x: x[1], reverse=True) else: groups[group_name].sort(key=lambda x: x[0]) return groups # ------------------------------ # Example Usage # ------------------------------ sample_data = [ ("Newtown", 12500), ("Riverwood", None), ("Oakville", 6200), ("Maple Creek", 8900), ("Sunnydale", ""), ("Hilltown", 9500), ("Lakeside", 15000), ("Pineville", "7200") # String-based population example ] # First sort the data with your existing logic sorted_data = sort_population(sample_data) # Then group it grouped_data = group_population_data(sorted_data) # Print the final grouped results for group, cities in grouped_data.items(): print(f"\n--- {group} ---") for city, pop in cities: print(f"{city}: {pop if pop is not None else 'No data'}")
Step 3: Integrate with Text File Input
If your data is coming from a text file (e.g., comma-separated lines), add this helper function to load the data first:
def load_city_data(file_path): data = [] with open(file_path, 'r') as f: next(f) # Skip the header line if your file has one for line in f: line = line.strip() if not line: continue city, pop = line.split(',', 1) pop = pop.strip() # Convert empty strings to None for easier handling pop = None if not pop else pop data.append((city, pop)) return data # Load, sort, group, and save results file_data = load_city_data("city_populations.txt") sorted_file_data = sort_population(file_data) grouped_file_data = group_population_data(sorted_file_data) # Write grouped results to a new file with open("grouped_city_populations.txt", 'w') as f: for group, cities in grouped_file_data.items(): f.write(f"\n--- {group} ---\n") for city, pop in cities: f.write(f"{city}: {pop if pop is not None else 'No data'}\n")
Key Notes to Adjust for Your Use Case
- NA Flexibility: The code handles
None, empty strings, and non-numeric values as NA—tweak the condition if your "no data" marker is something specific (like "N/A"). - Sorting: Numeric groups stay sorted descending to match your original code, but you can remove that step if you don't need within-group sorting.
- Edge Cases: The
try-exceptblock ensures your code doesn't break if population values are stored as strings (like "7200") or have typos.
内容的提问来源于stack exchange,提问作者tvalentine

