如何自动提取列表中-90至90角度段的对应数据索引?
分段提取对应数据的Python脚本方案
实现思路
核心是定位每个数据段的起始索引(对应Angles中的-90)和结束索引(对应起始点之后的第一个90),再通过切片提取data中对应范围的内容。
代码实现
Angles = [-90, -60, -30, 0, 30, 60, 90, -90, -45, 0, 45, 90, -90, -60, -45, 0, 45, 60, 90] data = [50, 120, 0, 75, 231, 623, 30, 40, -45, 0, 3215, 955, 40, -440, -45, 210, 445, 660, 190] # 收集所有-90的起始索引 start_indices = [idx for idx, val in enumerate(Angles) if val == -90] segmented_data = [] for start_idx in start_indices: # 找到当前起始点之后第一个90的索引,结束切片要+1(因为Python切片左闭右开) end_idx = Angles.index(90, start_idx + 1) + 1 # 提取对应data段 segmented_data.append(data[start_idx:end_idx]) # 查看结果 for i, seg in enumerate(segmented_data): print(f"第{i+1}段数据: {seg}")
关键说明
- 使用
enumerate遍历Angles,收集所有值为-90的索引作为段起始点; - 调用
Angles.index(90, start_idx + 1)确保从起始点之后查找第一个90,避免匹配到起始点之前的元素; - Python切片是左闭右开,所以结束索引要+1,才能包含90对应的data元素。
运行输出
第1段数据: [50, 120, 0, 75, 231, 623, 30] 第2段数据: [40, -45, 0, 3215, 955] 第3段数据: [40, -440, -45, 210, 445, 660, 190]
内容的提问来源于stack exchange,提问作者asiantaco
相关产品推荐
相关产品推荐

