【问题标题】:list the coordinates that has same y coordinate coordinate into a list将具有相同 y 坐标坐标的坐标列出到列表中
【发布时间】:2019-02-11 02:59:54
【问题描述】:

我有一个列表

Sorted list : [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]

我需要将具有相同 y 坐标的坐标放入列表中,例如

[(40, 8), (301,8)]
[(8, 181), (274, 181)]

这个可以吗?

【问题讨论】:

  • 纯代码编写请求在 Stack Overflow 上是题外话——我们希望这里的问题与特定编程问题有关——但我们很乐意帮助您自己编写!告诉我们what you've tried,以及您遇到的问题。这也将有助于我们更好地回答您的问题。

标签: python list coordinates


【解决方案1】:

您可以使用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)]

【讨论】:

    【解决方案2】:

    我建议使用这样的字典:

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

    【讨论】:

    • 感谢您的建议。您建议的方法有效。但问题是它只返回一对。但是有两对 y 值相同。你能建议如何解决这个问题吗?
    • 我不确定你的意思?我编辑了我的答案以显示在您的示例列表上运行时它给出的结果。您可以迭代 paired_lists.values() 以仅获取坐标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2016-04-27
    相关资源
    最近更新 更多