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

如何从元组列表的嵌套字典中提取所有start键对应的值?

提取所有"start"值的解决方案

原始数据

listoftuples = [
    ( { 'd1':[ {'start': 1.2, 'end': 2.7}, {'start': 3.0, 'end': 4.0} ] }, [] ), 
    ( { 'd2':[ {'start': 1.4, 'end': 2.3}, {'start': 3.2, 'end': 4.3} ] }, [] ), 
    ( { 'd3':[ {'start': 1.7, 'end': 2.0}, {'start': 3.5, 'end': 4.0} ] }, [] ), 
    ( { 'd4':[ {'start': 1.5, 'end': 2.4}, {'start': 3.7, 'end': 4.2} ] }, [] ), 
    ( { 'd5':[ {'start': 1.3, 'end': 2.0}, {'start': 3.0, 'end': 4.0} ] }, [] ), 
    ( { 'd6':[ {'start': 1.1, 'end': 2.6}, {'start': 3.6, 'end': 4.0} ] }, [] ), 
]

期望结果

result_list = [1.2,3.0,1.4,3.2,1.5,3.5,1.3,3.7,1.3,3.0,1.1,3.6]

方法一:嵌套循环(直观易懂)

逐层遍历数据结构,提取每个start值:

result_list = []
# 遍历列表中的每个元组
for item in listoftuples:
    # 获取元组内的目标字典(元组第一个元素)
    target_dict = item[0]
    # 遍历字典里的区间列表(字典的值)
    for interval_list in target_dict.values():
        # 遍历区间列表里的每个字典
        for interval in interval_list:
            # 提取start值并添加到结果列表
            result_list.append(interval['start'])

print(result_list)

方法二:列表推导式(简洁高效)

用Python列表推导式将嵌套逻辑压缩为一行,逻辑与嵌套循环完全一致:

result_list = [interval['start'] 
               for item in listoftuples 
               for interval_list in item[0].values() 
               for interval in interval_list]

print(result_list)

内容的提问来源于stack exchange,提问作者José Angel Bernal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:37:08