【问题标题】:How to pick some items in list of lists and check if it exists in list of tuples如何在列表列表中选择一些项目并检查它是否存在于元组列表中
【发布时间】:2020-12-08 02:45:40
【问题描述】:

假设我有元组列表edges = [(0,1),(0,3),(0,4),(1,2),(1,3),(1,4),(2,3),(2,4)] 和列表列表 vertices = [[1,4,2,3,0],[3,0,1,2,4],[2,3,0,1,4],[1,3,2,1,4],[0,3,2,4,1]]。然后我想检查顶点中每个列表的第一个和最后一个元素是否存在于边中,然后做一些事情。

例如,在第一个顶点列表中,即 [1,4,2,3,0],第一个和最后一个项目是 10 在边 (0,1) 中退出(它可能是 (0,1) 和 (1, 0)) 然后对所有顶点列表做一些相同的事情。我不知道如何继续下面的代码。

edges = [(0,1),(0,3),(0,4),(1,2),(1,3),(1,4),(2,3),(2,4)]
vertices = [[1,4,2,3,0],[3,0,1,2,4],[2,3,0,1,4],[1,3,2,1,4],[0,3,2,4,1]]

for i in range(len(vertices)):
    if vertices[i][0] and vertices[i][-1] in edges:
        do stuff...

【问题讨论】:

    标签: python list for-loop if-statement tuples


    【解决方案1】:

    如果您想将您的值与元组进行比较,那么您可能应该将它们变成元组:

    for idx, i in enumerate(vertices):
        t = tuple((i[0], i[-1]))
        if t in edges:
            print(f'Item {idx} matches edge {t}.')
        elif t[::-1] in edges:
            print(f'Item {idx} matches edge {t[::-1]}.')
    
    Out:
    Item 0 matches edge (0, 1).
    Item 2 matches edge (2, 4).
    Item 3 matches edge (1, 4).
    Item 4 matches edge (0, 1).
    

    编辑:一个更通用的版本,为您提供顶点和边匹配项的索引。

    for idx, i in enumerate(vertices):
        t = tuple((i[0], i[-1]))
        for j, k in enumerate(edges):
            if t == k:
                print(f'Vertex {idx} matches edge {t} at index {j}.')
            elif t[::-1] == k:
                print(f'Vertex {idx} matches edge {t[::-1]} at index {j}.') 
    
    Out:
    Vertex 0 matches edge (0, 1) at index 0.
    Vertex 2 matches edge (2, 4) at index 7.
    Vertex 3 matches edge (1, 4) at index 5.
    Vertex 4 matches edge (0, 1) at index 0. 
    

    【讨论】:

    • 是的,正如尼克所说,它应该包括 (1,0) 和 (0,1)。
    • @Aras,更新了答案,所以现在它包括两者。
    • (0,1) 可以有任何索引。您的代码仅适用于这种特定情况。你能概括一下吗?
    • @Aras,已更新。我希望这就是你所需要的。
    猜你喜欢
    • 1970-01-01
    • 2013-12-12
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多