Find all tuples related to a certain string in Python

前端 未结 3 2017
谎友^
谎友^ 2021-01-15 14:49

I am trying to find all tuples related to a string, not just matched to it. Here is what I made:

from itertools import chain

data = [(\'A\',\'B\'),(\'B\',\'         


        
3条回答
  •  感动是毒
    2021-01-15 15:14

    A very naive solution, might not be efficient for complicated trees.

    data = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('B', 'F'),
            ('F', 'W'), ('W', 'H'), ('G', 'Z')]
    init = ['A']
    result = []
    while init:
        initNEW = init.copy()
        init = []
        new = 0
        for edge in data:
            for vertex in initNEW:
                if edge[0] == vertex:
                    result.append(edge)
                    init.append(edge[1])
                    new += 1
        for i in range(len(result) - new, len(result)):
            data.remove(result[i])
    print(result)
    # [('A', 'B'), ('B', 'C'), ('B', 'D'), ('B', 'F'), ('F', 'W'), ('W', 'H')]
    

提交回复
热议问题