擅长:python、mysql、java
<p>@volatile已经解释了为什么会发生这种情况,但为了便于参考,您可以编写一个类似的函数,避免使用生成器嵌套作用域。你知道吗</p>
<pre><code>def random(seed):
x = seed
while True:
x = ( x * 16807 ) % 2147483647
yield x
</code></pre>
<p>当像<code>for rand_num in random(100)</code>一样迭代时,这将给您一个伪随机数序列。您还可以根据需要获取新的随机数,而无需使用for循环:<code>rand_gen = random(100); rand_num = next(rand_gen)</code>。你知道吗</p>
<p>您可以看到随机数生成器是生成器的一种自然用法:函数更短、更清晰,可以以自然的方式(<code>for...in</code>和<code>next</code>)使用,并且不太容易出现由于<code>nonlocal</code>而产生的错误。有关生成器和<code>yield</code>的更好解释,请参见<a href="https://stackoverflow.com/questions/231767/the-python-yield-keyword-explained">this question</a>。你知道吗</p>