提供 python 代码:识别列表中的元素何时以三个为一组交换位置

Provide the python code: Identify when the elements of a list exchanged positions in groups of three

假设我有一个表示图形顶点的列表。

 lista = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

我获取列表并计算顶点的自同构群。这 returns 给我一个新列表,我的顶点以三个为一组进行交换。输出列表如下:

 output = [0,1,2,3,4,5,7,8,6,10,11,9,13,14,12,16,17,15,19,20,18]

如果您手动分析列表,您可以确定元素以三个为一组进行交换。在我们的示例中,

changed_elements = [[7,8,6],[10,11,9],[13,14,12],[16,17,15],[19,20,18]]

我想要python代码或伪代码如何识别和组合一起交换的三个元素

def identify_cycles(l1, l2):
    d1 = {val: idx for idx, val in enumerate(l1)} 
    # This assumes unique values in input l1, but I think the question does too
    out = []
    for idx, val in enumerate(l1):
        curr = l2[idx]
        if curr == val or any(val in s for s in out):
            continue # If this value doesn't move, or we've seen this cycle, then skip
        x = set([val]) # Otherwise, we're at the start of a new cycle
        while curr != val:
            x.add(curr) # The value at this index in l2 is also in this cycle
            curr = l2[d1[curr]] 
            # The next value in the cycle will be in l2 at the index that curr is at in l1
        out.append(x)
    return out

print(identify_cycles(lista, output))
# [{8, 6, 7}, {9, 10, 11}, {12, 13, 14}, {16, 17, 15}, {18, 19, 20}]

我相信以上应该能够识别任何长度大于 1 的循环。