我有一个列表
Sorted list : [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
我需要将具有相同y坐标的坐标带入类似列表中
[(40, 8), (301,8)]
[(8, 181), (274, 181)]
可以做到吗?
答案 0 :(得分:0)
我建议像这样使用字典:
coordinate_list = [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
paired_lists = {}
for x, y in coordinate_list:
if y in paired_lists:
paired_lists[y].append((x, y))
else:
paired_lists[y] = [(x, y)]
哪个让我
print(paired_lists)
# {8: [(40, 8), (301, 8)],
# 147: [(27, 147)],
# 181: [(8, 181), (274, 181)]}
答案 1 :(得分:0)
您可以使用itertools.groupby
来完成这项工作:
from itertools import groupby
lst = [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
for _, y in groupby(lst, lambda x: x[1]):
xs = list(y)
if len(xs) > 1:
print(xs)
# [(40, 8), (301, 8)]
# [(8, 181), (274, 181)]