生成列表的唯一排列的有效方法

问题描述

什么是生成列表的唯一排列的有效方法

我尝试过

set(itertools.permutations(['a','b','c','a','c']))

但是,随着列表中不同元素的数量增加,它花费的时间太长。有时甚至冻结PC。

解决方法

如果您不需要获取所有可能的排列并且列表很长,则可以使用random.shuffle并检查生成的排列是否已经在旅途中生成。

示例如下:

import random 

a = [a very long list]

existed_permutations = set()

for i in range(10):
    random.shuffle(a)
    # shuffle a in place
    new_permutation = tuple(a)
    if new_permutation in existed_permutations:
        continue 
    else:
        print(new_permutation)
        existed_permutations.add(new_permutation)

但是,如果您的列表很长并且需要所有排列,那么可能没有一种简便的方法可以加快处理速度。

,

itertools recipes处获取输入,并从@fusion处得到答复,我认为以下代码有效。

def random_permutation(iterable,r=None):
    "Random selection from itertools.permutations(iterable,r)"
    pool = tuple(iterable)
    r = len(pool) if r is None else r
    return tuple(random.sample(pool,r))


l = ['a','b','c','a','b']

t_start = time.clock()

existed_permutations = set()

for _ in range(10):
    new_permutation = random_permutation(l)
    if new_permutation in existed_permutations:
        print("dup")
        continue
    else:
        print(new_permutation)
        existed_permutations.add(new_permutation)

t_total = time.clock()
print("total time",t_total-t_start)