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, 任何人都可以解释一下这是如何运作的吗?
答案 0 :(得分:4)
other
是record
中每个prefs
的列表元素。
答案 1 :(得分: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))
所以会发生这样的事情:
other
,从而实例化它other
不等于person
scores
你发布的构造被称为列表理解,它可以是一个很好,整洁,快速的方式来编写可以是一系列正常循环等。
编辑(由moooeeeep提供): 关于列表理解的PEP202,以及实际的documentation。
答案 2 :(得分:0)
假设您没有编程经验 -
topMatches是你的功能。
其他是临时变量。此变量在topMatches函数中定义。在python中,您没有明确需要“声明”变量来创建它。
例如,
in c,
void topMatches( . , . , . )
{
int other;
.
.
.
}
你会有这样的东西,其他被定义为变量。
但在python中,如果我只是这样做,
for other in prefs:
<something something>
python编译器自己理解你要创建一个名为“other”的临时变量,该变量遍历循环。 (在你给出的例子中)。
相当于说,
for (int i;i<n;i++)
.
.
其中i是循环的变量迭代器。 (在C中)。
类似地,在Python中,“other”是本例中循环的变量迭代器。 希望这可以帮助!