我有一个带有矢量点的列表,我希望根据嵌套列表的第二个值y位置进行拆分。所以,points[0][1]
。
示例列表包含两个唯一的y高度:920
和940
。但是列表可以轻松达到10个独特的高度。
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] ] ]
答案 0 :(得分:1)
这是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)]]
答案 1 :(得分:0)
我在其x值列表中创建了y值的字典,然后迭代y值,为每个值创建子列表,并迭代x值,为每个值创建一个子列表。 / p>
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]]]