の 2 つまたは同じ値を持たないように、(x,y,z)
Python で3 タプルを生成しようとしています。さらに、変数およびは、別々の範囲およびで定義できます。そのようなタプルを生成できるようにしたいと思います。明らかな方法の 1 つは、各変数を呼び出して、 . これを行うためのより効率的な方法はありますか?x
y
z
x
y
z
(0,p)
(0,q)
(0,r)
n
random.random()
x=y=z
1 に答える
1
必要な要素を生成するジェネレーターを作成できます。たとえば、次のようになります。
def product_no_repeats(*args):
for p in itertools.product(*args):
if len(set(p)) == len(p):
yield p
それに貯水池サンプリングを適用します。
def reservoir(it, k):
ls = [next(it) for _ in range(k)]
for i, x in enumerate(it, k + 1):
j = random.randint(0, i)
if j < k:
ls[j] = x
return ls
xs = range(0, 3)
ys = range(0, 4)
zs = range(0, 5)
size = 4
print reservoir(product_no_repeats(xs, ys, zs), size)
于 2012-10-11T09:45:14.197 に答える