基于嵌套列表唯一值拆分向量点列表(按y坐标分组)
嘿,这个分组需求其实很好解决,不管你有10个还是更多唯一的y值,用Python的字典相关方法就能轻松搞定。下面给你详细的实现方案:
实现思路与代码示例
1. 基础实现:按y值顺序分组
如果需要保持y值在原列表中首次出现的顺序,可以先提取唯一y值,再逐个筛选分组:
points = [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920), (418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)] # 提取唯一y值并保留首次出现的顺序 unique_ys = list(dict.fromkeys(y for x, y in points)) # 按y值分组,同时把元组转为列表格式 newPoints = [] for y in unique_ys: current_group = [[x, y] for x, y_coord in points if y_coord == y] newPoints.append(current_group) # 输出结果 print(newPoints)
运行后会得到你期望的结构:
[[[418, 920], [558, 920], [726, 920], [858, 920], [906, 920], [1042, 920]], [[418, 940], [558, 940], [734, 940], [865, 940], [899, 940], [1034, 940]]]
2. 更高效的写法:用defaultdict自动分组
如果想让代码更简洁高效,可以借助collections模块的defaultdict,它会自动为每个新的y值创建空列表,省去手动去重的步骤:
from collections import defaultdict points = [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920), (418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)] # 初始化分组字典 grouped_dict = defaultdict(list) for x, y in points: grouped_dict[y].append([x, y]) # 把字典的值转为列表,得到最终结果 newPoints = list(grouped_dict.values())
这个方法不管有多少个唯一y值都能完美适配,而且代码更紧凑。
小提示
- 如果不需要保持y值的出现顺序,直接用
set(y for x, y in points)提取唯一y值也可以,但集合是无序的,分组顺序可能和原列表不一致。 - 代码中特意把原元组
(x,y)转换成了列表[x,y],完全匹配你给出的newPoints格式要求。
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

