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

Python嵌套列表循环异常:仅遍历首个元素未迭代后续列表项

循环逻辑问题

你的代码里写了两层完全无业务意义的嵌套循环,导致程序永远卡在第一组数据的处理阶段,根本走不到后续子列表的遍历:

  • 第一层无效循环:for x in range(ids[1]) 会把价格值作为循环次数,第一组数据价格是22900,仅这一层就要跑22900轮
  • 第二层无效循环:for y in range(ids[0]) 会把商品ID值作为循环次数,第一组数据ID是47348,每轮x循环里还要再跑47348次
  • 两层循环叠加后,光处理第一组数据就要发起22900*47348超过10亿次接口请求,程序会一直卡在这个阶段,自然不会处理后面的子列表数据。
修正方法

直接删除这两层多余的嵌套循环,外层遍历拿到每组ID和目标价格后,发起一次对应接口请求即可,修正后代码:

id_ucprice = [[47348, 22900], [48340, 14700], [4834934, 14700], [348348, 15300]]

for ids in id_ucprice:
    item_id, target_price = ids[0], ids[1]
    post_data = {
        'price': target_price,
        'overpriced_email_price_change': False,
        'apply_to_all': False,
    }
    response = requests.post(f'apiurl/{item_id}/pricing', cookies=cookies, headers=headers, json=post_data)
    update_data = json.loads(response.text)
    response_price = update_data['priceCents']
    r_item = update_data['name']
    r_id = update_data['id']
    if response_price == target_price:
        print(style.MAGENTA + f'[{datetime.now()}] => Updated Price: {response_price/100:.2f} | ID = > {r_id} | Item = > {r_item}')

注意:如果业务确实需要对单条数据做重复请求/重试,不要直接用ID、价格这种业务数值当循环次数,单独定义明确的重试次数常量,避免出现天量无效请求打崩接口、卡死本地程序的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:03:12