Python“在这里。“建筑”在哪里

2024-09-28 23:51:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这是PyBrain网站的摘录。我了解大部分的情况,但有一句话把我完全难住了。我以前从未在python代码中见过这样的东西。以下是整个循环的上下文:

    for c in [0, 1, 2]:
        #have no friggin idea how this next line works
        here, _ = where(tstdata['class']==c)
        plot(tstdata['input'][here, 0], tstdata['input'][here, 1], 'o')

奇怪的“where”限定符来自NumPy,我知道它在做什么。不过,我从没见过“这里”这样用。有人能解释清楚这是怎么回事吗?你知道吗


Tags: no代码inforinputhere网站have
2条回答

pybrain正在使用结果对多维数组进行切片。你知道吗

>>> a
array([[3, 1, 0, 2],
       [1, 2, 1, 2],
       [1, 3, 3, 0],
       [0, 1, 0, 0]])

>>> b
array([3, 3, 1, 2])

>>> np.where(b==3)
(array([0, 1]),)

天真地使用它,要么返回高维数组,要么做一些不可靠的事情:

>>> a[np.where(b==3),0]
array([[3, 1]])

您可以解压元组或执行以下操作以返回预期结果:

>>> a[np.where(b==3)[0],0]
array([3, 1])

这是危险的原因:

>>> here, _ = np.where(b==3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

要更改上述内容:

here= where(tstdata['class']==c)
plot(tstdata['input'][here[0], 0], tstdata['input'][here[0], 1], 'o')

没有什么神奇的,where是一个简单的函数,在其他地方定义,它返回一个由两个元素组成的元组,并将它们自动解包到here变量和_变量。如果不使用函数where,而使用简单的tuple

>>> here, _ = ("a", "b")
>>> here
'a'
>>> _
'b'

相关问题 更多 >