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

标签 python arrays numpy combinations python-itertools

我想创建一个 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) 得到所有这些包含 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

关于python - 在 numpy 中创建不同大小列表的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73162972/

相关文章:

python - Numpy 数组点积

python - 为什么在尝试使用 SharedMemoryManager (python 3.8) 替代 BaseManager 时会出现 NameError 错误?

python - 将 py2app 与 Matplotlib 及其 Tex 格式一起使用?未找到 Dvipng

java - 将 char[] 转换为 byte[]

ios - TableViewCells 数组在更新 TableView 后重新排序

python - 平滑 numpy/pandas 中的一系列加权值

python - 在电报机器人中,/未按编码弹出/大写

python - 如何从 Python 的 LineString 列表创建 GeoJSON

c++ - 如何使用 new 运算符在表达式中聚合初始化 STL 容器?

python - 掩码时 Numpy 数组维度丢失