Python如何查找并展示算法定位到的包含目标数据的城市记录
代码修复方案
现有代码的核心错误
- 找人口最小值的逻辑完全错误:
- 初始值错误将第三个数组元素(整条城市记录)赋值给
min,实际应该取第一条记录的人口字段(索引为2的数值)作为初始最小值 - 比较逻辑反向:要找最小值应该判断当前城市人口是否小于现有最小值,才更新最小值,原代码写反了比较符号
- 索引调用错误:最后输出时用人口数值作为
relevant_cities的索引,完全不符合列表索引的调用规则
- 初始值错误将第三个数组元素(整条城市记录)赋值给
- 人口合法性校验存在类型错误:校验不通过重新输入的人口值没有转float,后续运算会报错
修复后完整代码
def createArray0fRecords(length): # City, Country, Population in Millions, Main Language city_records = ["", "", 0.0,""] city_array = [city_records]*length return city_array def populateRecords(city_array): for counter in range(0, len(city_array)): print("") print("Please enter the city") city=input() print('Please enter the country') country=input() print("Please enter the population in millions") population=float(input()) while population < 0: print(population," isn't a valid answer. Please input a number greater than 0.") # 修复:重新输入的人口转为float population=float(input()) print("Please enter the main language") language = input() city_array[counter] = [city, country, population, language] return city_array def main_program(): print("How many cities will you be entering?") length = int(input()) city_array = createArray0fRecords(length) city_array = populateRecords(city_array) # 修复:初始最小值取第一条记录的人口字段 min_pop = city_array[0][2] # 修复:比较逻辑调整为找更小的人口值 for i in range(len(city_array)): if city_array[i][2] < min_pop: min_pop = city_array[i][2] relevant_cities = [c for c in city_array if c[2] == min_pop] # 修复:直接遍历输出所有符合条件的城市 for city in relevant_cities: print(f"最低人口城市信息:城市名{city[0]},所属国家{city[1]},人口{city[2]}百万,主要语言{city[3]}") main_program()
修改说明
- 修正了人口校验逻辑:输入非法值重新录入时,将输入内容强制转为float,避免后续类型不匹配报错
- 重写了最小值查找逻辑:
- 初始最小值取第一条城市记录的人口数值(
city_array[0][2]) - 遍历所有城市时,仅对比人口字段,当当前城市人口小于现有最小值时更新最小值
- 初始最小值取第一条城市记录的人口数值(
- 修正了输出逻辑:直接遍历筛选出的最低人口城市列表,输出所有字段内容,避免非法索引调用
内容的提问来源于stack exchange,提问作者b00bl0v3r
相关产品推荐
相关产品推荐

