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

如何基于索引对应列表匹配嵌套字典指定Runner的Status并修复冗余结果

解决方案

问题根源

你当前的多层循环大概率没绑定market_id_list和selection_id_list的索引对应关系,而是遍历了所有market的所有runner,再遍历所有selectionId,导致同一个marketId匹配了多个不相关的selectionId,从而输出冗余结果。

正确实现思路

  1. 先把market_id_list和selection_id_list按索引配对,形成(market_id, selection_id)的元组列表,确保每一组都是对应关系。
  2. 遍历每一组配对,在resulted_market_books中找到对应的market字典,再在其runners里筛选出匹配selectionId的runner,取出status。

代码示例

# 将两个列表按索引配对,确保一一对应
market_selection_pairs = list(zip(market_id_list, selection_id_list))

# 遍历每一组目标配对
for target_market_id, target_selection_id in market_selection_pairs:
    # 定位对应的market字典
    for market_book in resulted_market_books:
        if market_book['marketId'] == target_market_id:
            # 在runners中查找指定selectionId的条目
            for runner in market_book['runners']:
                if runner['selectionId'] == target_selection_id:
                    print(f"Market {target_market_id} - Selection {target_selection_id}: {runner['status']}")
                    # 找到目标runner后立即跳出循环,避免冗余遍历
                    break
            # 找到对应market后跳出循环,不用再检查其他market
            break

效率优化方案

如果resulted_market_books数据量较大,建议先将其转换为以marketId为键的字典,避免重复遍历整个列表:

# 预处理:把resulted_market_books转成字典,key为marketId,value为对应的market_book
market_book_dict = {book['marketId']: book for book in resulted_market_books}

market_selection_pairs = list(zip(market_id_list, selection_id_list))

for target_market_id, target_selection_id in market_selection_pairs:
    # 直接通过key获取对应的market_book
    market_book = market_book_dict.get(target_market_id)
    if not market_book:
        print(f"Market {target_market_id} 不存在")
        continue
    # 查找目标runner
    for runner in market_book['runners']:
        if runner['selectionId'] == target_selection_id:
            print(f"Market {target_market_id} - Selection {target_selection_id}: {runner['status']}")
            break
    else:
        # 若runner循环未触发break,说明没找到对应selectionId
        print(f"Market {target_market_id} 中未找到Selection {target_selection_id}")

核心注意点

  • 找到匹配的runner或market后,必须用break跳出对应循环,这是解决冗余结果的关键。
  • 用zip绑定两个列表的索引关系,确保每一组marketId和selectionId严格对应,不会出现乱匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:15:38