1
def topMatches(prefs,person,n=5,similarity=sim_pearson):
  scores=[(similarity(prefs,person,other),other)
                  for other in prefs if other!=person]  
  scores.sort()
  scores.reverse()
  return scores[0:n]

我只是在 topmatches 函数中调用另一个函数,我怀疑其他工作是如何工作的,我没有在其他地方定义它我也没有将它传递给函数 topmatches, 谁能解释我这是如何工作的?

4

3 回答 3

4

other是每个recordin的列表元素prefs

于 2012-06-11T07:10:15.257 回答
3

你可以将你的展开scores=[(similarity(prefs,person,other),other) for other in prefs if other!=person]到这样的地方,看看发生了什么。

scores = []
for other in prefs:
    if other != person:
        scores.append((similarity(prefs, person, other))

所以会发生这样的事情:

  1. 您创建一个名为 scores 的空列表
  2. 您遍历首选项,并将该元素的值放入变量中,other从而实例化它
  3. 你检查以确保other不等于person
  4. 如果没有,你调用你的相似性函数并将结果附加到scores

您发布的结构称为列表理解,它可以是一种很好、简洁、快速的方式来编写一系列正常循环等。

编辑(由 moooeeeep 提供):

列表理解上的PEP202和实际文档

于 2012-06-11T07:12:07.963 回答
0

假设您没有编程经验 -

topMatches 是您的功能。

other 是一个临时变量。此变量在 topMatches 函数内部定义。在 python 中,您不需要明确地“声明”一个变量来创建它。

例如,

在 c 中,

void topMatches( . , . , . )
{
  int other;

.
.
.
}

你会有这样的东西,其中 other 被定义为一个变量。

但是在python中,如果我只是这样做,

for other in prefs:
<something something>

python 编译器自己理解您想要创建一个名为“other”的临时变量,该变量正在遍历您的循环。(在你给出的例子中)。

相当于说,

for (int i;i<n;i++)
. 
. 

其中 i 是循环的变量迭代器。(在 C 中)。

同样,在 Python 中,“other”是本例中循环的变量迭代器。希望这可以帮助!

于 2012-06-11T07:22:12.823 回答