使用排列循环在 python3 中形成新数组

Use permutation cycles to form new arrays in python3

我有一个数组a = [[1,2,3,4,5,6,7,8,9,10],[4,1,6,2,3,5,8,9,7,10]], where lets say a1 = [1,2,3,4,5,6,7,8,9,10] and a2 = [4,1,6,2,3,5,8,9,7,10],我从中构造了循环排列。请注意,a1 是一个排序数组。例如,在我的例子中,周期是;

c = [[4, 2, 1], [6, 5, 3], [8, 9, 7], [10]]
  lets say c1 = [4, 2, 1]
           c2 = [6, 5, 3]
           c3 = [8, 9, 7]
           c4 = [10]

现在我想按如下方式形成新数组 a11a22

我有一种方法可以给出给定排列中的所有循环,但是从中构造新数组似乎很复杂。 python3 中的任何实现此目的的想法将不胜感激。

--------------------

获取循环;

import numpy as np
import random

def cx(individual):
    c = {i+1: individual[i] for i in range(len(individual))}
    cycles = []

    while c:
        elem0 = next(iter(c)) # arbitrary starting element
        this_elem = c[elem0]
        next_item = c[this_elem]

        cycle = []
        while True:
            cycle.append(this_elem)
            del c[this_elem]
            this_elem = next_item
            if next_item in c:
                next_item = c[next_item]
            else:
                break

        cycles.append(cycle)

    return cycles
aa = cx([4,1,6,2,3,5, 8,9,7,10])
print("array: ", aa)

您可以使用 itertools.permutations 获得 a 项的不同排列,然后使用 itertools.cycle 循环遍历将 a 的子列表项映射到它们的子列表项的字典索引,并使用映射压缩 c 的子列表以生成遵循循环字典指定的索引的序列:

a = [[1,2,3,4,5,6,7,8,9,10],[4,1,6,2,3,5,8,9,7,10]]
c = [[4, 2, 1], [6, 5, 3], [8, 9, 7], [10]]
from itertools import cycle, permutations
print([[d[i] for i in range(len(d))] for l in permutations(a) for d in ({p[n]: n for s, p in zip(c, cycle({n: i for i, n in enumerate(s)} for s in l)) for n in s},)])

这输出:

[[1, 2, 6, 4, 3, 5, 7, 8, 9, 10], [4, 1, 3, 2, 5, 6, 8, 9, 7, 10]]