我有一个包含 10 个元素的数组,正在寻找最快方法在 Python 中用这 10 个元素随机生成 n 个大小为 m 的组合。
我必须对所有可能的组合大小(m 从 1 到元素数量)执行此操作,并且 n 也会变化,当可能的组合数量增加时,它也会增加。
For example if my input array is: [a, b, c, d, e, f, g, h, i, j]
for n = 4 and m = 3 the output should be:
(e, b, c)
(i, a, d)
(g, j, e)
(i, f, e)
There can't be twice the same element in one permutation.
我知道 itertool 函数可以生成给定大小的所有组合,但我只需要 n 个组合,而不是全部。所以我不确定使用 itertools 是解决我的问题的最快解决方案(因为我必须在所有生成的组合中随机选择 n 个组合)。
最佳答案
独特元素
对于这种方法,请确保传递的m
(样本大小)值不大于数组
(总体大小)大小。或者您可以添加 if 语句来检查 m
值。
import random
def generate_combinations(array, m, n):
"""Generate n random combinations of size m"""
if m > len(array): # Changing the m value to array length if it is greater than length of array
m = len(array)
return [random.sample(array, k=m) for _ in range(n)] # for unique element
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 5 # Number of combinations
m = 10
print(generate_combinations(array, m, n))
示例输出
[[8, 1, 2, 5, 4, 3, 6, 7, 10, 9],
[9, 6, 7, 1, 8, 2, 10, 3, 4, 5],
[8, 3, 7, 10, 6, 9, 2, 5, 1, 4],
[10, 8, 9, 2, 6, 5, 7, 4, 1, 3],
[5, 4, 1, 7, 10, 6, 3, 9, 8, 2]]
对于非唯一元素
import random
def generate_combinations(array, m, n):
"""Generate n random combinations of size m using list comprehension"""
return [random.choices(array, k=m) for _ in range(n)]
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 5 # Number of combinations
m = 10
print(generate_combinations(array, m, n))
示例输出
[[9, 8, 4, 2, 5, 4, 5, 5, 6, 1],
[2, 6, 10, 3, 6, 1, 7, 6, 2, 4],
[1, 9, 7, 9, 8, 2, 10, 1, 1, 7],
[10, 4, 5, 7, 8, 9, 5, 1, 4, 1],
[9, 3, 3, 5, 9, 4, 9, 8, 10, 6]]
或者您可以使用numpy
(唯一)
import numpy as np
def generate_combinations(array, m, n):
if m> len(array):
m = len(array)
return [np.random.choice(array, (1, m), replace=False).tolist()[0] for _ in range(n)]
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 5 # Number of combinations
m = 10
print(generate_combinations(array, m, n))
示例输出
[[6, 7, 9, 10, 8, 4, 1, 2, 3, 5],
[8, 5, 2, 10, 7, 3, 9, 4, 1, 6],
[8, 1, 4, 10, 3, 6, 9, 7, 2, 5],
[7, 4, 8, 5, 3, 9, 6, 10, 1, 2],
[1, 8, 7, 3, 9, 2, 5, 4, 10, 6]]
关于python - 在Python中生成n个组合的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76610174/