如何将用户输入对应县的人口转为可进行数学运算的数值变量?
解决方案:将县人口转换为可运算的数值
要实现获取用户输入对应县的人口数值并用于数学运算,需要解决三个核心问题:去除人口字符串的千位分隔符、匹配用户输入与字典键、处理异常输入,以下是具体实现方案:
1. 预处理人口数据(推荐方式)
原字典中人口是带千位逗号的字符串,无法直接运算,最简便的方式是初始化字典时直接存储整数,避免重复处理:
AZcounties = { "Maricopa": 4496588, "Pima": 1052030, "Pinal": 449557, "Yavapai": 242253, "Mohave": 217692, "Yuma": 206990, "Coconino": 145052, "Cochise": 126052, "Navajo": 108147, "Apache": 65623, "Gila": 53589, "Santa Cruz": 47883, "Graham": 39050, "La Paz": 16408, "Greenlee": 9404, }
如果无法修改原字典,可在取值时动态转换:
# 取出字符串后移除逗号,再转为整数 population = int(AZcounties[county].replace(',', ''))
2. 处理用户输入的匹配问题
用户输入的县名可能存在大小写差异(如maricopa或MARICOPA),可以将输入转换为标题格式,确保和字典键一致:
county = input("Enter county: ").strip().title()
3. 完整代码示例(含运算演示)
AZcounties = { "Maricopa": 4496588, "Pima": 1052030, "Pinal": 449557, "Yavapai": 242253, "Mohave": 217692, "Yuma": 206990, "Coconino": 145052, "Cochise": 126052, "Navajo": 108147, "Apache": 65623, "Gila": 53589, "Santa Cruz": 47883, "Graham": 39050, "La Paz": 16408, "Greenlee": 9404, } print("Which Arizona county would you like to see the population of?") county = input("Enter county: ").strip().title() # 判断输入的县名是否存在 if county in AZcounties: population = AZcounties[county] print(f"{county}的人口数值:{population}") # 数学运算示例:计算人口的15% fifteen_percent = population * 0.15 print(f"{county}人口的15%为:{int(fifteen_percent)}") # 运算示例:计算与Pima县的总人口差 pima_pop = AZcounties["Pima"] pop_diff = abs(population - pima_pop) print(f"{county}与Pima县的人口差为:{pop_diff}") else: print("输入的县名不存在,请检查拼写!")
内容的提问来源于stack exchange,提问作者Nint
相关产品推荐
相关产品推荐

