Python:在2D数组中查找所有可能的唯一双索引组合

时间:2017-03-24 23:20:20

标签: python arrays python-3.x numpy itertools

我的numpy数组大致相当于:

data = ([1, 2, 3], [4, 5, 6], [7, 8, 9])

我想找到这些值的所有唯一双索引组合。换句话说,我想要所有可能的组合而不重复行或列索引(类似于正确解决数独谜题)。例如,所需的输出将是:

output >> ([1, 5, 9], [1, 6, 8], [2, 4, 9], [2, 6, 7], [3, 4, 8], [3, 5, 7])

并且此输出可以由它们对应的索引表示:     ([0] [0],[1] [1],[2] [2]),([0] [0],[1] [2],[2] [1]),([0] [1],[1] [0],[2] [2]),([0] [1],[1] [2],[2] [0]),([0] [2], [1] [0],[2] [1]),([0] [2],[1] [1],[2] [0])

我尝试过使用itertools.permutations,虽然它确实找到了每个唯一行的数据的所有可能排列,但它不会将每个列视为唯一的一个)

我希望每行和每列只有一个值

我对python很新,有没有人建议我如何做到这一点?

1 个答案:

答案 0 :(得分:2)

from itertools import permutations

data = ([1, 2, 3], [4, 5, 6], [7, 8, 9])

output = [[row[y] for row, y in zip(data, permutation)]
          for permutation in permutations(range(len(data)))]

编辑:评论中的问题已更改为仅产生不包含0的结果。此外,由于len(data)为100,我们无法使用permutations生成所有结果上面然后过滤它们;这需要永远。它们必须正确选择,如下:

def get_nonzero_perms(data, remaining_indices=None):
    if not data:
        yield []
        return
    if remaining_indices is None:
        remaining_indices = list(range(len(data)))
    row = data[0]
    for i in remaining_indices:
        value = row[i]
        if value == 0:
            continue
        for perm in get_nonzero_perms(data[1:], [j for j in remaining_indices if j != i]):
            yield [value] + perm


for p in get_nonzero_perms(([2, 8, 0, 0], [0, 3, 9, 4], [0, 0, 5, 1], [4, 6, 0, 7])):
    print(p)

输出:

[2, 3, 5, 7]
[2, 9, 1, 6]
[2, 4, 5, 6]
[8, 9, 1, 4]
[8, 4, 5, 4]
相关问题