python random.shuffle()在while循环中

时间:2012-07-01 14:12:59

标签: python python-3.x

我有一个清单:

    k = [1,2,3,4,5]

现在我想要将此列表的3个排列列在另一个列表中但是当我这样做时:

    x = []
    i = 0
    while i < 3:
        random.shuffle(k)
        x.append(k)
        i += 1

我的结果是x在x中的相同排列的3倍,如下所示:

    x = [[1,3,5,2,4], [1,3,5,2,4], [1,3,5,2,4]]

代替我想要的东西,像这样:

    x = [[1,5,4,2,3], [1,3,5,2,4], [5,3,4,1,2]]

请注意,由于收集k中的数据以将k置于循环内部的方式,因此不可能,因为我知道这将解决问题。真正的代码是:

    def create_random_chromosomes(genes):
        temp_chromosomes = []
        chromosomes = []
        i = 0
        while i < 2000:
            print(genes)
            random.shuffle(genes)
            temp_chromosomes.append(genes)
            i += 1
        print(temp_chromosomes)
        for element in temp_chromosomes:
            if element not in chromosomes:
                chromosomes.append(element)
        return chromosomes

1 个答案:

答案 0 :(得分:8)

随机播放列表会将其更改为就地,并且您正在创建对同一列表的3个引用。在改组之前创建列表的副本

x = []
for i in range(3):
    kcopy = k[:]
    random.shuffle(kcopy)
    x.append(kcopy)

我也简化了你的循环;只需使用for i in range(3)。或者,将其置于完整方法的上下文中:

def create_random_chromosomes(genes):
    temp_chromosomes = []
    chromosomes = []
    for i in range(2000):
        print(genes)
        randomgenes = genes[:]
        random.shuffle(randomgenes)
        temp_chromosomes.append(randomgenes)
    print(temp_chromosomes)
    for element in temp_chromosomes:
        if element not in chromosomes:
            chromosomes.append(element)
    return chromosomes

您可以使用set清除欺骗行为来进一步简化上述内容:

def create_random_chromosomes(genes):
    chromosomes = set()
    randomgenes = genes[:]
    for i in range(2000):
        random.shuffle(randomgenes)
        chromosomes.add(tuple(randomgenes))
    return list(chromosomes)

这使用随机基因列表的元组副本来适应设置内容的hashable约束。

然后,您甚至可以确保返回2000个唯一项目,无论如何:

def create_random_chromosomes(genes):
    chromosomes = set()
    randomgenes = genes[:]
    while len(chromosomes) < 2000:
        random.shuffle(randomgenes)
        chromosomes.add(tuple(randomgenes))
    return list(chromosomes)