Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生成列表唯一排列的有效方法_Python_Unique_Permutation - Fatal编程技术网

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

Python 生成列表唯一排列的有效方法,python,unique,permutation,Python,Unique,Permutation,生成列表的唯一排列的有效方法是什么 我试过这个 set(itertools.permutations(['a','b','c','a','b','c','a','b','c',')) 但是,随着列表中不同元素数量的增加,所需时间太长。有时甚至会冻结电脑。如果您不需要获取所有可能的排列,而且列表很长,您可以使用random.shuffle并检查生成的排列是否已在移动中生成 例如: 随机导入 a=[非常长的列表] 已存在的排列=集合() 对于范围(10)内的i: 随机。洗牌(a) #洗牌 新排列=元

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

我试过这个

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


但是,随着列表中不同元素数量的增加,所需时间太长。有时甚至会冻结电脑。

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

例如:

随机导入
a=[非常长的列表]
已存在的排列=集合()
对于范围(10)内的i:
随机。洗牌(a)
#洗牌
新排列=元组(a)
如果现有排列中的新排列排列:
继续
其他:
打印(新排列)
已存在的排列。添加(新排列)
但是,如果您的列表很长,并且您需要所有的排列,那么可能没有一种简单的方法来加快速度。

从@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', 'c', '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)

这回答了你的问题吗?你需要用它们做什么?因为您可以通过迭代
itertools.permutations的结果来生成一个fews,因为使用
set()
它会强制等待,直到生成所有的置换,是的,这可能需要相当长的时间(数小时、数天)@Karthik,速度是个问题。我试着使用
set
。这个链接中的另一个答案据说比set方法慢。@azro我必须迭代每个排列。每个排列将用于昂贵的计算。itertools.permutations()的结果包含重复的元素。@fusion答案中给出的代码符合您的目的,您指的是tubble(a)的第一个元素吗
new_permutation=tuple(a)[0]
@fustion我喜欢在排列数量较大时进行随机排列的想法。我检查了以下各项的计时<代码>l=['a','b','c','a','b','c','a','b','c','a','b']a=列表(itertools.permutations(l))随机。随机播放(a)
阅读耗时7分钟,随机播放耗时47分钟。