在^{}模块中,有一个从iterable返回随机组合的方法。下面是两个版本的代码,一个用于Python 2.x,一个用于Python 3.x——在这两种情况下,您都在使用generator,这意味着您没有在内存中创建一个大的iterable。
假设Python 2.xdef 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)
在您的情况下,这样做很简单:>>> import random
>>> 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)
>>> n = 10
>>> m = 3
>>> print(random_combination(range(n), m))
(3, 5, 9) # Returns a random tuple with length 3 from the iterable range(10)
对于Python 3.x
在Python 3.x的情况下,您将xrange调用替换为range,但是用例仍然是相同的。def random_combination(iterable, r):
"Random selection from itertools.combinations(iterable, r)"
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.sample(range(n), r))
return tuple(pool[i] for i in indices)