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

Python if条件分支如何将数据存入嵌套列表并遍历取值

代码修改方案

按以下规则调整即可满足需求,原有业务逻辑完全保留:

  • 在商品列表遍历逻辑前,初始化空嵌套列表L = []用于存储符合条件的数据
  • 在if price > lowest_ask:判断分支内,保留原有my_ids[price] = [lowest_ask - 100]价格计算逻辑,同时将当前匹配的商品ID、价格组成子列表追加到L中
  • 所有商品遍历完成后,直接通过for循环遍历L,读取每个子列表索引0(商品ID)、索引1(商品价格)的值传入后续JSON处理逻辑即可
修改后可直接运行的完整代码
import time
from datetime import datetime
import requests
# 原有全局变量:style、params、cookies、headers、API接口前缀请保持原有定义不变

def main():
    print(style.YELLOW + f'[{datetime.now()}] => getting listing ids[]')
    response = requests.get('api', params=params, cookies=cookies, headers=headers)
    
    response_data_ids = response.json()
    
    if response.status_code == 200:
        print(style.GREEN + f'[{datetime.now()}] => got listing ids[status:{response.status_code}]')
    else:
        print(style.RED + f'[{datetime.now()}] => error [{response.status_code}][{response}][auth error]')
        time.sleep(3) # 重试延迟
        main()
    
    listing_ids = [result['id'] for result in response_data_ids['results']]
    
    my_ids = {}
    # 初始化要求的嵌套存储列表
    L = []
    for i in range(len(listing_ids)):
        response = requests.get(f'API{listing_ids[i]}/pricing', cookies=cookies, headers=headers) 
        response_price = response.json()
        
        price = response_price['priceCents']
        # 原变量名id改为item_id,避免覆盖Python内置id函数引发潜在问题,不影响原有业务逻辑
        item_id = response_price['stockItemId']
        item = response_price['product']['name']
        lowest_ask = response_price['currentLowestPrice']

        print(style.MAGENTA + f'[{datetime.now()}] => Current Price: {price/100:.2f} | Lowest Price: {lowest_ask/100:.2f} | ID: {item_id} | Item: {item}')
        
        if price > lowest_ask:
            # 保留原有的价格计算逻辑
            my_ids[price] = [lowest_ask - 100]
            print(style.WHITE + f'[{datetime.now()}] => over lowest ask[{price/100:.2f}][{item_id}]')
            # 将符合条件的[id, price]存入嵌套列表
            L.append([item_id, price])
            
        response = requests.get(f'API/{listing_ids[i]}', cookies=cookies, headers=headers) 
        response_status = response.json()
        pending = response_status["status"]
        
        if pending == "reserved":
            print(style.WHITE + f'[{datetime.now()}] => Pending Sold[{price/100:.2f}][{item_id}]')
    
    # 嵌套列表遍历使用示例,替换为实际JSON处理逻辑即可
    for goods in L:
        target_id = goods[0]
        target_price = goods[1]
        # 示例打印,实际使用时替换为你的业务逻辑
        print(f"正在处理匹配商品:ID={target_id},价格(分)={target_price},价格(元)={target_price/100:.2f}")

main()
注意事项
  • 最终生成的L结构完全符合要求,格式为[[id, price], [id, price], ...]
  • 遍历取值时,子列表索引0对应商品ID,索引1对应商品原价格(单位为分,与原代码取值逻辑一致)
  • 原有my_ids字典的计算、存储逻辑完全未改动,不会影响原有依赖该字典的业务

内容的提问来源于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 05:48:09