Python 基于唯一值拆分嵌套列表

Python 基于唯一值拆分嵌套列表,python,split,Python,Split,我得到了一个带有向量点的列表,我想根据嵌套列表的第二个值,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

我得到了一个带有向量点的列表,我想根据嵌套列表的第二个值,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)

我在x值列表中创建了一个y值字典,然后遍历y值,为每个值创建一个子列表,然后遍历x值,为每个值创建一个子列表

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_dict = dict()

for point in points:
    x = point[0]
    y = point[1]
    if y in y_dict.keys():
        #already found this y
        y_dict[y].append(x)
    else:
        #haven't found this y
        y_dict[y] = [x]

newPoints = []

for y in y_dict.keys():
    sublist = []
    for x in y_dict[y]:
        sublist.append([x, y])
    newPoints.append(sublist)

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]]]

我想不清楚你想要的结果应该是什么,请具体说明。@Michhawiedenmann,我理解。但是马腾给了我一个理想的解决方案。如果你花时间让你的问题更具可读性,那么其他有同样问题并发现你的问题的人会从中受益更多。谢谢@Maarten,现在,由于我仍在学习Pyton,我将坚持使用“为我理解的列表”解决方案。这是一个多么庞大的算法,可以很容易地通过内置的
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_dict = dict()

for point in points:
    x = point[0]
    y = point[1]
    if y in y_dict.keys():
        #already found this y
        y_dict[y].append(x)
    else:
        #haven't found this y
        y_dict[y] = [x]

newPoints = []

for y in y_dict.keys():
    sublist = []
    for x in y_dict[y]:
        sublist.append([x, y])
    newPoints.append(sublist)

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]]]