Python itertools 双元素排列

Python itertools permutations with double elements

我正在使用 python (2.7.2),并且我需要列表中所有不重复的排列。更准确地说,

 for i in itertools.permutations([1,2,3]): print i

正确给出

(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

但现在我正在寻找可以执行以下操作的东西

for i in myfunction([1,2,2]): print i
(1,2,2)
(2,2,1)
(2,1,2)

而 itertools 会给出该列表两次(或者,对于 ([1,1,1]) 作为输入,它只重复六次)。 这基本上介于 itertools.permutations 和 itertools.combinations 之间。 我尝试使用集合,但我尝试过的所有解决方案总是会产生新问题,并且永远无法匹配所需的输出。

看来你想要这套。

s = []
for i in itertools.permutations([1,2,2]):
    s.append(i)
print(set(s))

给出:

{(1, 2, 2), (2, 2, 1), (2, 1, 2)}

或者,不将对象保存到变量:

for i in set(itertools.permutations([1,2,2])):
    print(i)