Python报错Unsupported operand type(s) for -: 'float' and 'str'求解
问题根因
你构造的confirmedcases列表是交替存储「浮点型确诊数」和「字符串型日期」的混合类型列表,做减法运算时必然会出现浮点数和字符串运算的类型错误。
修正建议
1. 调整存储结构,不要混合存储病例数和日期
建议用两个单独的列表分别存储日期和对应的确诊数,修正后可运行的代码如下:
import requests import json country = "France" url = 'https://covid-api.mmediagroup.fr/v1/history?country='+country+'&status=confirmed' request = requests.get(url) dct1 = json.loads(request.text) key1 = "All" key2 = "dates" # 单独存储日期和对应的累计确诊数 date_list = [] confirmed_list = [] for datekey in dct1[key1][key2]: confirmed_list.append(float(dct1[key1][key2][datekey])) date_list.append(datekey) # 倒序对齐,让时间从早到晚排列 confirmed_list.reverse() date_list.reverse() current_high = 0 new_cases = [] high_date = "" for i in range(1, len(confirmed_list)): daily_new = confirmed_list[i] - confirmed_list[i-1] new_cases.append(daily_new) if daily_new > current_high: current_high = daily_new high_date = date_list[i] # 同步记录新增最高值对应的日期 print("单日新增最高值:", current_high) print("最高新增对应的日期:", high_date) input("press any key")
2. 其他修复说明
- 补充了原代码缺失的
requests、json库引入语句 - 你原代码后半段给
dct1重新赋值为dct1[i]是错误写法,原dct1是接口返回的字典,不能用数字索引取值 - 累计确诊已经提前转成float存入
confirmed_list,后续做减法不需要重复转换类型
内容的提问来源于stack exchange,提问作者Geoffrey Seamons
相关产品推荐
相关产品推荐

