并行随机分布

时间:2016-09-19 17:11:40

标签: python random iterator generator

我在python中有两个迭代器,两者都应该遵循相同的“随机”分布(两者应该并行运行)。例如:

class Iter1(object):
   def __iter__(self):
       for i in random_generator():
          yield i

class Iter2(object):
   def __iter__(self):
       for i in random_generator():
          yield i

for el1, el2 in zip(Iter1(), Iter2()):
    print '{} {}'.format(el1, el2)

输出应该像是:

0.53534 0.53534
0.12312 0.12312
0.19238 0.19238

如何定义random_generator(),使其为两个迭代器创建相同的随机分布并行

注意:

  • 他们应该并行运行
  • 我无法提前生成序列(这是一个流媒体,所以我不知道序列的大小)

感谢。

2 个答案:

答案 0 :(得分:2)

random_generator的每次调用指定相同的种子:

import random

def random_generator(l, seed=None):
    r = random.Random(seed)
    for i in range(l):
        yield r.random()


class Iter1(object):
   def __init__(self, seed):
       self.seed = seed

   def __iter__(self):
       for i in random_generator(10, self.seed):
          yield i


class Iter2(object):
   def __init__(self, seed):
       self.seed = seed
   def __iter__(self):
       for i in random_generator(10, self.seed):
          yield i


# The seed can be any hashable object, but don't use None; that
# tells random.seed() to use the current time. But make sure that
# Python itself isn't using hash randomization.
common_seed = object()
for el1, el2 in zip(Iter1(common_seed), Iter2(common_seed)):
    print '{} {}'.format(el1, el2)

答案 1 :(得分:0)

无法以这种方式控制随机世代号。如果你想这样做,你应该创建自己的随机功能。但是作为另一种pythonic和更简单的方法,您可以创建一个对象并使用itertools.tee来复制迭代器对象,使其具有相同的随机序列结果:

In [28]: class Iter1(object):
             def __init__(self, number): 
                 self.number = number
             def __iter__(self):
                 for _ in range(self.number):
                   yield random.random()
   ....:                 

In [29]: 

In [29]: num = Iter1(5)

In [30]: from itertools import tee

In [31]: num, num2 = tee(num)

In [32]: list(zip(num, num2))
Out[32]: 
[(0.485400998727448, 0.485400998727448),
 (0.8801649381536764, 0.8801649381536764),
 (0.9684025615967844, 0.9684025615967844),
 (0.9980073706742334, 0.9980073706742334),
 (0.1963579685642387, 0.1963579685642387)]