[英]Trying to understand this Python code
我是python的新手,但是我不理解此python代码的最后一行 。 这是什么意思?
import np as numpy
def goat_door(prizedoors, guesses):
#strategy: generate random answers, and
#keep updating until they satisfy the rule
#that they aren't a prizedoor or a guess
result = np.random.randint(0, 3, prizedoors.size)
while True:
bad = (result == prizedoors) | (result == guesses)
if not bad.any():
return result
result[bad] = np.random.randint(0, 3, bad.sum())
奖池和猜测是np.random.choice(2,模拟数量)
结果是一个数组,我不知道result [bad]是什么意思。
编辑:我只是将import np编写为numpy
result
是一个长度为prizedoors.size
的numpy ndarray
,其中每个元素都是从[0, 3)
随机抽取的。 例如:
>>> result = np.random.randint(0, 3, 5)
>>> result
array([1, 1, 2, 0, 1])
bad
是一个布尔数组,无论result == prizedoors
或result == guesses
,它都是True。 prizedoors
和guesses
也可能是布尔数组。 无论如何, bad
结局看起来像
>>> bad
array([ True, True, True, False, True], dtype=bool)
bad.sum()
计算bad.sum()
的数量:
>>> bad.sum()
4
result[bad]
选择result
的元素,其中bad == True
:
>>> result[bad]
array([1, 1, 2, 1])
最后,最后一行用新的随机值填充坏值(不一定是好值,只有新值):
>>> result[bad] = np.random.randint(0, 3, bad.sum())
>>> result
array([1, 1, 0, 0, 1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.