if条件判断通过后如何创建数组并修复Python类型报错
问题修复与功能实现
报错原因
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'的触发根源是接口返回的priceCents或lowestPriceCents字段存在空值(None),代码未做非空判断直接执行除以100的运算就会报错。除此之外原代码还存在3处逻辑缺陷:
over_priced列表初始化位置错误,放在商品遍历循环内部,每次循环都会被重置为空列表,且遍历空列表的逻辑完全无效,根本无法存储符合条件的商品- 无论商品是否满足
price > lowest_ask条件,都会打印“over lowest ask”的日志,和预期逻辑不符 - 直接通过字典下标取值,接口字段缺失时会直接触发
KeyError导致程序崩溃
具体修改点
- 新增字段非空校验:通过字典
.get()方法取值,对priceCents、lowestPriceCents、商品ID、商品名称等核心字段做空值判断,空值直接打印提示跳过当前商品,从根源避免空值运算报错 - 将
over_priced列表初始化移到商品遍历逻辑外层,满足price > lowest_ask条件时,直接将(商品ID, 商品价格)格式的元组追加到列表中,实现嵌套存储要求 - 新增差值计算逻辑:对有效
lowest_ask值计算lowest_ask - 100(单位为分,对应比最低报价低1元的目标价格),可按需打印或存储 - 调整日志打印逻辑,仅当商品确实满足高于最低报价的条件时,才打印对应提示和计算出的差值
- 补充缺失的模块导入、接口状态码校验逻辑,避免运行时基础报错
修正后完整代码
import requests from datetime import datetime # 以下参数替换为实际业务使用的值即可 params = {} cookies = {} headers = {} def main(): over_priced = [] # 列表初始化移到外层,持久存储所有符合条件的商品 print(f'[{datetime.now()}] => getting listing ids[]') response = requests.get('api', params=params, cookies=cookies, headers=headers) # 先校验列表接口状态再解析数据 if response.status_code != 200: print(f'error getting listing ids[{response.status_code}][{response.text}]') return print(f'[{datetime.now()}] => got listing ids[{response.status_code}]') response_data_ids = response.json() listing_ids = [result['id'] for result in response_data_ids.get('results', [])] for listing_id in listing_ids: response = requests.get(f'api{listing_id}/pr', cookies=cookies, headers=headers) # 单商品接口报错直接跳过,不中断整体流程 if response.status_code != 200: print(f'[{datetime.now()}] => get item {listing_id} price failed, status code {response.status_code}') continue response_price = response.json() # 安全取值+空值校验 price = response_price.get('priceCents') product_info = response_price.get('product', {}) prod_id = product_info.get('id') item_name = product_info.get('name') lowest_ask = response_price.get('lowestPriceCents') # 任意核心字段为空直接跳过,避免运算报错 if None in [price, prod_id, item_name, lowest_ask]: print(f'[{datetime.now()}] => item {listing_id} field missing, skip') continue # 单位转换后打印信息 price_yuan = price / 100 lowest_ask_yuan = lowest_ask / 100 print(f'[{datetime.now()}] => Current Price: {price_yuan:.2f} | Lowest Price: {lowest_ask_yuan:.2f} | ID: {prod_id} | Item: {item_name}') # 满足价格条件才做存储和差值计算 if price > lowest_ask: # 按要求存储(id, price)格式的条目 over_priced.append( (prod_id, price) ) # 计算lowest_ask - 100 差值(单位:分),转元单位方便查看 target_price_cents = lowest_ask - 100 target_price_yuan = target_price_cents / 100 print(f'[{datetime.now()}] => over lowest ask[{price_yuan:.2f}][{prod_id}], target bid price: {target_price_yuan:.2f}') # 遍历完成后可直接使用over_priced列表做后续业务处理 print(f'[{datetime.now()}] => all overpriced items collected: {over_priced}') if __name__ == '__main__': main()
补充说明
- 最终生成的
over_priced列表内每个元素为(商品ID, 价格(单位:分))格式的元组,如果需要存储元为单位的价格,把append语句里的price替换为price_yuan即可 lowest_ask - 100默认计算的是比当前最低报价低1元(100分)的定价,如果需要调整价差直接修改减数即可- 所有接口请求都加了状态码校验,字段取值统一用
.get()方法避免KeyError,空值条目直接跳过,不会再触发None类型运算的报错
内容的提问来源于stack exchange,提问作者user19422024
相关产品推荐
相关产品推荐

