在python3中使用置换循环形成新数组

在python3中使用置换循环形成新数组,python,arrays,python-3.x,genetic-algorithm,cyclic,Python,Arrays,Python 3.x,Genetic Algorithm,Cyclic,我有一个数组a=[[1,2,3,4,5,6,7,8,9,10],[4,1,6,2,3,5,8,9,7,10]],其中a1=[1,2,3,4,5,6,7,8,9,10]和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]

我有一个数组
a=[[1,2,3,4,5,6,7,8,9,10],[4,1,6,2,3,5,8,9,7,10]],其中a1=[1,2,3,4,5,6,7,8,9,10]和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]
现在我想形成新的数组
a11
a22
,如下所示;

我有一种方法可以给出给定排列中的所有循环,但是从中构造新的数组似乎很复杂。任何在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
子列表项映射到其索引的dict,并使用映射压缩
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]]