如何在Python中对XML文件中的国家条目排序并输出前10条人口密度与经济数据?
Solution: Get Top 10 Entries by Calculated Metrics
Hey there! Let's fix this up so you can get the top 10 entries sorted by economic output (since that's the key metric you mentioned calculating). The issue with your current code is that you're processing each country one by one and printing immediately—you aren't storing all the data somewhere so you can sort it and pick the top 10 later. Here's how to adjust it:
Modified Code
import xml.etree.ElementTree as ET tree = ET.parse("europe.xml") stuff = tree.getroot() lst = stuff.findall("country") # Create an empty list to store all country data with our calculated metrics country_data = [] for item in lst: try: # Parse raw values from XML (handle potential missing/invalid data) gdp = int(item.find("gdppc").text) pop = int(item.find("population").text) area = float(item.find("area").text) # Calculate required metrics economy_total = gdp * pop density = float(pop / area) # Add data to our list as a tuple (easy to sort later) country_data.append( (economy_total, item.get("name"), density) ) except (AttributeError, ValueError) as e: # Skip countries with bad/missing data to avoid crashes print(f"Skipping country {item.get('name', 'unknown')}: {str(e)}") continue # Sort countries by economic total (descending order = largest first) sorted_countries = sorted(country_data, key=lambda x: x[0], reverse=True) # Grab the top 10 entries top_10 = sorted_countries[:10] # Print results in a clean format print("Top 10 Countries by Economic Output (GDP × Population):") print("-------------------------------------------------------") for rank, (economy, name, density) in enumerate(top_10, 1): print(f"{rank}. {name}") print(f" Economic Total: {economy:,}") # Add commas for readability print(f" Population Density: {density:.2f} people per unit area\n")
Key Changes Explained
- Data Storage: We collect all calculated metrics into a list of tuples instead of printing immediately. This lets us sort and filter the entire dataset later.
- Sorting: The
sorted()function uses a lambda to sort by the first element of each tuple (economic total).reverse=Trueensures the largest values come first. - Top 10 Selection: Using
[:10]slices the sorted list to keep only the first 10 entries—your top performers. - Error Handling: The
try/exceptblock skips countries with missing tags or non-numeric values, preventing your code from crashing unexpectedly. - Readability: Added numbered ranking, comma formatting for large numbers, and clear section headers to make output easier to scan.
Bonus: Sort by Population Density Instead
If you want the top 10 by density instead of economic output, just change the sorting key in the sorted() line to target the third element of the tuple:
sorted_countries = sorted(country_data, key=lambda x: x[2], reverse=True)
内容的提问来源于stack exchange,提问作者shirley
相关产品推荐
相关产品推荐

