列表中所有可能的组合,而没有任何成员重复其位置

时间:2018-11-20 07:15:27

标签: python combinations

我有一个数字列表,我需要所有组合,而没有任何成员重复其在列表中的位置。

示例:如果我有{1、2、3},则{3、2、1}是不可接受的,因为“ 2”在同一位置。唯一好的结果是{3,1,2}和{2,3,1}。我需要更大的规模,到目前为止,我已经有了:

import itertools
x = [1, 2, 3, 4, 5, 6, 7]
y = 5
comb = []
comb.extend(itertools.combinations(x,y))
print(comb)

这给了我所有的组合,但是我需要消除那些在相同位置具有相同成员的组合,最好不仅是在打印时而且在梳理列表中。

2 个答案:

答案 0 :(得分:1)

从您编写的预期输出来看,您似乎在寻找排列而不是组合

import itertools
import numpy as np
x = [1, 2, 3]
y = 3

no_repeat_permutations = []
for candidate_perm in itertools.permutations(x,y):
    for p in map(np.array, no_repeat_permutations):
        if any(np.array(candidate_perm) == p):
            break
    else:
        no_repeat_permutations.append(candidate_perm)

print(no_repeat_permutations)

>>> [(1, 2, 3), (2, 3, 1), (3, 1, 2)]

我正在使用numpy进行逐元素比较,如果过去结果中的任何逐元素比较都是True,我们将跳过此排列。 在某种情况下,我们找不到这样的比较,我们输入else语句并保存排列。

有关for-else的更多说明,请参见this SO question

答案 1 :(得分:1)

不确定我是否了解...但是也许这就是您想要的...

from collections import deque
from itertools import islice

def function(x, y):
    Q = deque(x)
    states = set()
    for _ in range(len(x)):
        states.add(tuple(islice(Q, 0, y)))
        Q.appendleft(Q.pop())
    return states

x = [1, 2, 3, 4, 5, 6, 7]
y = 5
resp = function(x, y)
print(resp)
>>> {(5, 6, 7, 1, 2), (1, 2, 3, 4, 5), (7, 1, 2, 3, 4), (2, 3, 4, 5, 6), (4, 5, 6, 7, 1), (6, 7, 1, 2, 3), (3, 4, 5, 6, 7)}