Python国家转大洲代码:一段正常一段报unhashable error的原因咨询
Hey there! Let's break down exactly why your first snippet works flawlessly while the second one throws that confusing unhashable error.
The Core Difference Between Your Two Codes
- First code: You’re using a list comprehension to loop through each country in your
countrieslist, passing individual country names (strings) to thecountry_to_continentfunction. Thepclibrary methods (country_name_to_country_alpha2, etc.) are built to accept single string inputs, so this aligns perfectly with their expectations. - Second code: You’re passing the entire list of countries directly to
country_to_continent. The problem here is thatpc.country_name_to_country_alpha2expects a single, hashable value (like a string) — but lists are unhashable in Python. Most lookup/conversion methods under the hood use hash tables to map inputs to outputs, and unhashable types (like lists, dictionaries, etc.) can’t be used as keys in these tables, hence the error.
What’s an "Unhashable Error" Anyway?
In Python, hashable objects have a fixed value that doesn’t change over their lifetime (think strings, integers, or tuples with immutable contents). Unhashable objects are mutable (like lists, where you can add/remove items after creation), so their hash value would shift if the object is modified — making them incompatible with operations that rely on stable hash values (like the country-to-code lookup the pc library is doing).
How to Fix the Second Code
If you want your function to handle a list directly instead of looping outside it, modify it to accept either a single country string or a list of strings:
def country_to_continent(country_input): # Handle both single country strings and lists if isinstance(country_input, str): country_input = [country_input] continents = [] for country_name in country_input: country_alpha2 = pc.country_name_to_country_alpha2(country_name) country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2) country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code) continents.append(country_continent_name) return continents # Now this will work! country_names = list(df['country']) country_to_continent(country_names)
Alternatively, you could stick with the reliable pattern from your first code (list comprehension) or use map for a concise approach:
country_names = list(df['country']) list(map(country_to_continent, country_names))
Either way, you’re ensuring individual country strings are passed to the pc library methods — which is exactly what they’re designed to handle.
内容的提问来源于stack exchange,提问作者Kevin Su

