简体   繁体   English

在元组列表中查找具有连续值的元组并将它们变成更大的元组

[英]Find tuples in a list of tuples, with consecutive values and turn them into bigger tuples

I have a list of tuples, each having two elements.我有一个元组列表,每个元组都有两个元素。 Example:例子:

my_tuples = [('black', 'grey'), ('red', 'orange'), ('blue', 'purple'), 
             ('orange', 'yellow'), ('grey', 'white'), ('yellow', 'cream')]

I am looking for an efficient way to find all the tuples whose first values are identical to second value of another one, make a triple of them, and continue adding values in this manner until all such chains are found.我正在寻找一种有效的方法来查找其第一个值与另一个元组的第二个值相同的所有元组,将它们组成三元组,并继续以这种方式添加值,直到找到所有这样的链。 In this example, it should give the following list back:在此示例中,它应该返回以下列表:

my_tuples_processed = [('black', 'grey', 'white'), ('blue', 'purple'), 
                       ('red', 'orange', 'yellow', 'cream')]

Any help on this would be appreciated.对此的任何帮助将不胜感激。

Using a dictionary to efficiently find the starting values and the connections, and using lists to efficiently concatenate the values ( Try it online! ):使用字典有效地查找起始值和连接,并使用列表有效地连接值( 在线尝试! ):

my_tuples_processed = []
d = dict(my_tuples)
for x in d.keys() - d.values():
    path = [x]
    while x in d:
        path.append(x := d[x])
    my_tuples_processed.append(tuple(path))

This assumes that no value appears twice as first or twice as second value (as discussed in the question's comments).这假设没有任何值出现两次是第一个值或第二个值的两倍(如问题评论中所讨论的)。

An iterator alternative mostly because I love iterators ( Try it online! ):迭代器的替代品主要是因为我喜欢迭代器( 在线尝试! ):

my_tuples_processed = []
d = dict(my_tuples)
def get():
    global x
    return (x := d.get(x))
for x in d.keys() - d.values():
    path = x, *iter(get, None)
    my_tuples_processed.append(path)

I add my own original solution before posting this question, simply for the sake of completelness.在发布这个问题之前,我添加了我自己的原始解决方案,只是为了完整起见。 But it is not really an efficient solution and the accepted answer is much preferable.但这并不是一个真正有效的解决方案,而且公认的答案更可取。

def sort_merge_tuples(list_tuples):
    my_tuples = list_tuples.copy()
    cc1 = 0
    while cc1 < len(my_tuples):
        my_t = my_tuples[cc1]
        cc2 = 0
        while cc2 < len(my_tuples):
            my_t2 = my_tuples[cc2]
            if my_t[-1] == my_t2[0]:
                new_tuple = my_t + my_t2[1:]
                my_tuples.remove(my_t)
                my_tuples.remove(my_t2)
                my_tuples.append(new_tuple)
                cc1 = 0
                break
            elif my_t2[-1] == my_t[0]:
                new_tuple = my_t2 + my_t[1:]
                my_tuples.remove(my_t)
                my_tuples.remove(my_t2)
                my_tuples.append(new_tuple)
                cc1 = 0
                break
            cc2 = cc2 + 1
        cc1 = cc1 + 1
    return my_tuples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM