我有一个包含向量点的列表,我想根据嵌套列表的第二个值(y 位置)对其进行分割。因此,点[0][1]
。
该示例列表包含两个唯一的 y 高度:920
和 940
。但列表可以轻松拥有 10 个唯一的 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)]
# Desired result:
newPoints = [ [ [x,920], [x,920] ], [ [x,940], [x,940] ] ]
最佳答案
这就是 collections.defaultdict
的用武之地:
from collections import defaultdict
new_points = defaultdict(list)
for point in points:
new_points[point[1]].append(point)
defaultdict(<class 'list'>, { 920: [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920)], 940: [(418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)] })
如果您需要列表,可以执行 new_points.values()
或 list(new_points.values())
[[(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920)], [(418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]]
关于python - 根据唯一值拆分嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814301/