我想知道,为什么这段代码会抛出一个类型错误以及如何修复它。
def uniform_generator(a, b):
while True:
b = uniform(loc=a, scale=b)
yield b.rvs(1)
num_gen = uniform_generator(1, 5)
numbers = [float(next(num_gen)[0]) for _ in range(1000)]
据我所知,我正在做的是向一个空数组添加1000个浮点数。有什么问题?我正在使用Python 3
追溯:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-133-42a9353c6a00> in <module>()
4 num_gen = uniform_generator(1, 5)
5 print(type(float(next(num_gen)[0])))
----> 6 numbers = [float(next(num_gen)[0]) for _ in range(1000)]
7
8 assert([1 <= num and num <= 5 for num in numbers])
<ipython-input-133-42a9353c6a00> in <listcomp>(.0)
4 num_gen = uniform_generator(1, 5)
5 print(type(float(next(num_gen)[0])))
----> 6 numbers = [float(next(num_gen)[0]) for _ in range(1000)]
7
8 assert([1 <= num and num <= 5 for num in numbers])
<ipython-input-107-8956bb825458> in uniform_generator(a, b)
2 while True:
3 b = uniform(loc=a, scale=b)
----> 4 yield b.rvs(1)
5
6 def normal_generator(mean, std):
c:\users\user\anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py in rvs(self, size, random_state)
468 kwds = self.kwds.copy()
469 kwds.update({'size': size, 'random_state': random_state})
--> 470 return self.dist.rvs(*self.args, **kwds)
471
472 def sf(self, x):
c:\users\user\anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py in rvs(self, *args, **kwds)
936 rndm = kwds.pop('random_state', None)
937 args, loc, scale, size = self._parse_args_rvs(*args, **kwds)
--> 938 cond = logical_and(self._argcheck(*args), (scale >= 0))
939 if not np.all(cond):
940 raise ValueError("Domain error in arguments.")
TypeError: '>=' not supported between instances of 'rv_frozen' and 'int'
答案 0 :(得分:1)
它不应该是一个发电机:
def uniform_generator(a, b):
# you want to rename it now, since it isn't a generator anymore
#while True:
b = uniform(loc=a, scale=b)
#yield b.rvs(1)
return b.rvs(1)
#num_gen = uniform_generator(1, 5)
# numbers = [float(next(num_gen)[0]) for _ in range(1000)]
numbers = [uniform_generator(1,5) for _ in range(1000)]
或者,你把它变成了一个像你一样的生成器,但你需要在1000之后打破它:
def uniform_generator(a, b, wanted):
for _ in range(wanted):
b = uniform(loc=a, scale=b)
yield b.rvs(1)
numbers = [n for n in uniform_generator(1,5, 1000)]
答案 1 :(得分:1)
将b作为均匀度传递,并在第一次迭代后覆盖它。只需将其重命名为:
def uniform_generator(a, b):
while True:
c = uniform(loc=a, scale=b)
yield c.rvs(1)