You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在可返回原数组不同组合的NumPy函数?

当然有啦!如果你想用NumPy生成原数组的各种组合,这里有几种常用的方法,根据你需要的组合类型来选:

NumPy生成数组不同组合的实用方法

1. 生成笛卡尔积(所有元素配对)

从NumPy 1.25版本开始,新增了numpy.cartesian_product函数,能直接生成多个数组的笛卡尔积,非常适合需要所有元素两两(或多元素)配对的场景。

import numpy as np

# 原数组
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])

# 生成两个数组的笛卡尔积
result = np.cartesian_product(arr1, arr2)
print(result)

输出结果:

[[1 3]
 [1 4]
 [2 3]
 [2 4]]

如果是单个数组的笛卡尔积(比如生成所有n位元素组合),只需重复传入数组即可:

arr = np.array([0, 1])
# 生成所有3位二进制数的组合
result = np.cartesian_product(arr, arr, arr)
print(result)

输出:

[[0 0 0]
 [0 0 1]
 [0 1 0]
 [0 1 1]
 [1 0 0]
 [1 0 1]
 [1 1 0]
 [1 1 1]]

2. 生成无重复元素的组合(不考虑顺序)

如果需要从数组中选出k个元素的所有无序且无重复组合,NumPy本身没有内置函数,但可以搭配Python标准库的itertools.combinations,再转成NumPy数组:

import numpy as np
from itertools import combinations

# 原数组
arr = np.array([1, 2, 3, 4])

# 选2个元素的所有无序组合
comb = combinations(arr, 2)
result = np.array(list(comb))
print(result)

输出结果:

[[1 2]
 [1 3]
 [1 4]
 [2 3]
 [2 4]
 [3 4]]

3. 生成排列(考虑顺序的组合)

如果需要考虑元素的顺序(即排列),可以用itertools.permutations配合NumPy实现:

import numpy as np
from itertools import permutations

# 原数组
arr = np.array([1, 2, 3])

# 选2个元素的所有排列
perm = permutations(arr, 2)
result = np.array(list(perm))
print(result)

输出结果:

[[1 2]
 [1 3]
 [2 1]
 [2 3]
 [3 1]
 [3 2]]

4. 生成带重复的组合(可重复选元素)

如果允许重复选择同一个元素(比如从[1,2]中选2个元素,允许出现[1,1]这种组合),可以用itertools.combinations_with_replacement:

import numpy as np
from itertools import combinations_with_replacement

arr = np.array([1, 2])
comb = combinations_with_replacement(arr, 2)
result = np.array(list(comb))
print(result)

输出结果:

[[1 1]
 [1 2]
 [2 2]]

内容的提问来源于stack exchange,提问作者aimf212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:57:30