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

Python嵌套列表遍历问题:如何提取各患者的start time生成对应子列表

问题分析与解决方法

你的代码核心问题是最内层的for c in range(3)循环——每提取一条观测的start时间,就会把这条时间重复添加到start_times的三个子列表中,最终每个子列表都积累了所有134条数据。

正确的循环写法

使用enumerate同时获取每个患者子列表的索引和数据,这样就能精准把对应患者的start时间放到start_times的对应子列表里:

start_times = [[] for _ in range(3)]

# 遍历patients时同时拿到索引和对应患者的观测数据
for idx, patient_obs in enumerate(patients):
    for obs in patient_obs:
        # 注意:原问题里键是"start time",如果你的实际数据键名是这个,要替换掉'start'
        start_times[idx].append(obs['start time'])

更简洁的列表推导式写法

如果不需要显式的for循环,用列表推导式可以一行搞定,效果完全一致:

# 外层遍历每个患者的子列表,内层提取该子列表里每条观测的start time
start_times = [[obs['start time'] for obs in patient] for patient in patients]

注意事项

原问题里提到字典键是"start time",但你当前代码里写的是b['start'],请确认实际数据的键名,避免因键名不匹配引发KeyError。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:10:32