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

时间:2015-06-02 11:23:12

标签: python random iterator itertools

我有一个带itertools.combinations(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.combinations对象中的元素数。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

只需制作随机组合,跟踪您之前看过的内容:

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))

您可能误解了所发现的功能;它与我上面的函数大致相同,但只生成一个随机组合,而不跟踪之前生成的内容。您应该在matrix上使用它,而不是matrix的所有组合。