如何产生列表的排列无&QUOT反向重复"在Python中使用生成器 [英] How to generate permutations of a list without "reverse duplicates" in Python using generators
问题描述
这是有关质疑<一个href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How产生在Python列表中的所有排列
如何产生的所有排列匹配以下条件的的如果两个排列是反对方(即[1,2,3,4]和[4,3,2, 1]),它们被认为是平等的,只是其中之一应该是最终的结果
例如:
permutations_without_duplicates ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
我置换含有独特的整数的列表。
I am permuting lists that contain unique integers.
产生排列的数量会很高,所以我想如果可能的话使用Python的发电机组。
The number of resulting permutations will be high so I'd like to use Python's generators if possible.
编辑:我想不储存所有排列的名单内存,如果可能的
I'd like not to store list of all permutations to memory if possible.
推荐答案
我有一个奇妙的随访,以SilentGhost的建议 - 发布一个单独的答案,因为评论的利润率将过于狭窄,包含code: - )
I have a marvelous followup to SilentGhost's proposal - posting a separate answer since the margins of a comment would be too narrow to contain code :-)
和itertools.permutations
是内置的(自2.6)和快速。我们只需要一个过滤条件,对于每一个(烫发,烫发[:: - 1])将完全接受其中的一个。由于OP说,项目总是不同的,我们就可以比较任意2个元素:
itertools.permutations
is built in (since 2.6) and fast. We just need a filtering condition that for every (perm, perm[::-1]) would accept exactly one of them. Since the OP says items are always distinct, we can just compare any 2 elements:
for p in itertools.permutations(range(3)):
if p[0] < p[-1]:
print p
它打印:
(0, 1, 2)
(0, 2, 1)
(1, 0, 2)
这工作,因为扭转排列总是翻转的关系!
P [0] LT; P [1]
或其它任何对也将工作,所以还必须在其中一半的排列你会得到一定的控制。
This works because reversing the permutation would always flip the relation!
p[0] < p[1]
or any other pair would also work, so you also have some control over which half of permutations you get.
我不知道是否有任何更多的effecient的方式来过滤。 和itertools.permutations
保障字典顺序,但词典的位置 P
和 P [:: - 1]
相关在一个相当复杂的方式。特别是,只停在中间不工作
I'm not sure if there is any more effecient way to filter. itertools.permutations
guarantees lexicographic order, but the lexicographic position p
and p[::-1]
are related in a quite complex way. In particular, just stopping at the middle doesn't work.
但我怀疑(没有检查),其内置的迭代器与2:1的过滤会胜过任何自定义实现。当然它赢得简单!
But I suspect (didn't check) that the built-in iterator with 2:1 filtering would outperform any custom implementation. And of course it wins on simplicity!
这篇关于如何产生列表的排列无&QUOT反向重复&QUOT;在Python中使用生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!