python - 根据唯一值拆分嵌套列表

标签 python split

我有一个包含向量点的列表,我想根据嵌套列表的第二个值(y 位置)对其进行分割。因此,点[0][1]。 该示例列表包含两个唯一的 y 高度:920940。但列表可以轻松拥有 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/

相关文章:

python - 使用返回函数中的变量作为另一个函数的参数

python - 根据条件替换来自不同文件的字符串

javascript - 我的 javascript 有困难

javascript - 如何使用 JavaScript 解析数据中包含逗号的 CSV 字符串?

python - 使用 django-configurations 拆分配置文件

python - 用 pandas 平均二维地理数据

python - 如何绘制 networkx 图的节点子集

java - 如何使用正则表达式将字符串按最后一个字符拆分?

python - 在 numpy 中对巨大的密集矩阵进行操作

java - 用逗号分割字符串并忽略双引号中的逗号