You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何判断嵌套折扣列表中是否存在大于等于45.0的数值

错误原因

你遇到的类型错误是因为discounts列表的每个元素都是[折扣数值元组, 商品ID字符串]格式的二级列表,直接将整个列表和浮点数做比较不符合语法规则。

实现方案

场景1:仅判断是否存在≥45.0的折扣值

可以用双层any()快速判断,只要存在任意一个符合要求的数值就返回True:

# 存在符合条件的折扣时返回True,否则返回False
has_target_discount = any(any(rate >= 45.0 for rate in item[0]) for item in discounts)
if has_target_discount:
    print("存在大于等于45.0的折扣数值")

场景2:需要定位符合条件的折扣对应的商品ID

可以逐层遍历取值后判断:

for discount_item in discounts:
    # 拆分当前元素的折扣元组和对应商品ID
    rate_tuple, product_id = discount_item
    for rate in rate_tuple:
        if rate >= 45.0:
            print(f"商品ID {product_id} 存在符合要求的折扣:{rate}")
            # 单个商品只要找到一个符合的就可以跳出内层循环,避免重复判断
            break

内容的提问来源于stack exchange,提问作者whyamihere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:21:00