Skip to main content
 首页 » 编程设计

Python "here, . . . where"构造

2025年05月04日16dudu

这是 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,我知道它在做什么。不过,我从来没有见过“这里”这样用过。有人可以准确解释这是在做什么吗?

请您参考如下方法:

没有什么神奇的,where 是一个简单的函数,在别处定义,它返回一个包含两个元素的元组,并分配 action auto 将它们解包到 here 变量,和 _ 变量。如果我们尝试使用简单的 tuple 而不是函数 where:

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