Python itertools创建随机子集的迭代器

Python itertools创建随机子集的迭代器,python,random,iterator,itertools,Python,Random,Iterator,Itertools,我有一个迭代器itertools.compositions(big_matrix,50)和big_matrix.shape=(65,x),所以大约有10^14个组合。我想得到这个组合的随机子集,比如10000个,也作为迭代器,以节省内存 我试过itertools的配方 def random_combination(iterable, r): "Random selection from itertools.combinations(iterable, r)" pool = tuple(i

我有一个迭代器
itertools.compositions(big_matrix,50)
big_matrix.shape=(65,x)
,所以大约有10^14个组合。我想得到这个组合的随机子集,比如10000个,也作为迭代器,以节省内存

我试过itertools的配方

def random_combination(iterable, r):
  "Random selection from itertools.combinations(iterable, r)"
  pool = tuple(iterable)
  n = len(pool)
  indices = sorted(random.sample(xrange(n), r))
  return tuple(pool[i] for i in indices)
但是
tuple(iterable)
创建一个包含10^14个值的元组,该函数不返回迭代器,而是返回一个数组

random.sample
不起作用,因为它无法获取
itertools.compositions
对象中的元素数


有什么方法可以做到这一点吗?

只需生成随机组合,跟踪您以前看到的内容:

def random_combinations(matrix, size):
    seen = set()
    n = len(matrix)
    while True:
        new_sample = tuple(sorted(random.sample(xrange(n), size)))
        if new_sample not in seen:
            seen.add(new_sample)
            yield tuple(matrix[i] for i in new_sample)
迭代所有可能的组合进行采样是没有效率的,您仍然会测试所有10^14个组合

上述生成器在每次迭代时选择一个随机组合;如果需要某个数字,请使用循环或
itertools.islice()
;挑选10个随机组合将是:

combinations_sample = list(islice(random_combinations(matrix, 50), 10))

您可能误解了您发现的函数的作用;它与上面的函数基本相同,但只生成一个随机组合,而不跟踪以前生成的组合。你应该在
矩阵
上使用它,而不是在
矩阵
的所有组合上使用它

我不明白你到底在做什么。你自己在创造这些组合吗?我在任何地方都看不到
itertools.combines
。@user3696412是的,这会创建随机组合,而不是全部,然后从中选择。