繁体   English   中英

在 numpy 中创建不同大小列表的所有可能组合

[英]Create all possible combinations of lists of different sizes in numpy

我想创建一个 numpy 数组,其中包含来自不同大小的多个列表的所有可能的项目组合:

a = [1, 2] 
b = [3, 4]
c = [5, 6, 7] 
d = [8, 9, 10]

在每个组合中,我想要 2 个元素。 我不希望有任何重复,也不希望同一列表中的项目混合在一起。

我可以使用np.array(np.meshgrid(a, b, c, d)).T.reshape(-1,3)获得所有此类组合,但我需要对,而不是三胞胎。 执行np.array(np.meshgrid(a, b, c, d)).T.reshape(-1,2)不起作用,因为它只是切断了原始数组的一列。

关于如何实现这一目标的任何想法?

所以 Itertools 非常适合这个。 您要做的第一件事是将您的列表合并为一个可迭代的列表(列表列表)。 第一步是获取列表的所有组合。

from itertools import combinations, product

a = [1, 2] 
b = [3, 4]
c = [5, 6, 7] 
d = [8, 9, 10]
total = [a,b,c,d]
for item in combinations(total, 2):
    print(item)

返回

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

您可以简单地遍历各个列表,如下所示

from itertools import combinations

a = [1, 2] 
b = [3, 4]
c = [5, 6, 7] 
d = [8, 9, 10]
total = [a,b,c,d]
for item in combinations(total, 2):
    for sub_item in item[0]:
        for second_sub_item in item[1]:
            print(sub_item, second_sub_item)

打印出来是

1 3
1 4
2 3
2 4
1 5
1 6
1 7
2 5
2 6
2 7
1 8
1 9
1 10
2 8
2 9
2 10
3 5
3 6
3 7
4 5
4 6
4 7
3 8
3 9
3 10
4 8
4 9
4 10
5 8
5 9
5 10
6 8
6 9
6 10
7 8
7 9
7 10

类似于 Olvin Roght 的评论,但如果你把你的子列表放在一个列表中,你可以这样做:

>>>> ls = [[1,2],[3,4],[5,6,7],[8,9,10]]
>>>> [item for cmb in combinations(ls, 2) for item in product(*cmb)]
[(1, 3), (1, 4), (2, 3), (2, 4), (1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (1, 8), (1, 9), (1, 10), (2, 8), (2, 9), (2, 10), (3, 5), (3, 6), (3, 7), (4, 5), (4, 6), (4, 7), (3, 8), (3, 9), (3, 10), (4, 8), (4, 9), (4, 10), (5, 8), (5, 9), (5, 10), (6, 8), (6, 9), (6, 10), (7, 8), (7, 9), (7, 10)]

如果您只想使用 numpy 而不使用 itertools,这是一个替代方案。

def all_combinations(arrays):
    """
    :param arrays: tuple of 1D lists.
        the functions returns the combinations of all these lists.
    :return: np.array of shape (len_out, 2).
        np.array of all the possible combinations.
    """
    len_array = np.asarray([len(elt) for elt in arrays])
    
    # the length of out is equal to the sum of the products 
    # of each element of len_array with another element of len_array
    
    len_out = (np.sum(len_array) ** 2 - np.sum(len_array ** 2)) // 2
    out, next_i = np.empty((len_out, 2), dtype=int), 0
    new_elt = arrays[0]

    for elt in arrays[1:]:
        out_elt = np.asarray(np.meshgrid(new_elt, elt)).T.reshape(-1, 2)
        next_j = next_i + len(out_elt)
        out[next_i: next_j] = out_elt
        next_i = next_j
        new_elt = np.concatenate((new_elt, elt))

    return out

例子:

>>> arrays = ([1, 2], [3, 4], [5, 6, 7], [8, 9, 10])
>>> all_combinations(arrays)
    [[ 1  3]
     [ 1  4]
     [ 2  3]
     ...
     ...
     [ 7  8]
     [ 7  9]
     [ 7 10]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM