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函数中调用了另一个函数,我的疑问是other是如何工作的,我在其他地方没有定义它,也没有将它传递给topmatches函数,谁能解释一下这是如何工作的?
回答:
你可以展开你的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))
所以发生的事情是这样的:
- 你创建了一个名为scores的空列表
- 你遍历prefs,并将该元素的值放入一个名为
other
的变量中,从而实例化它 - 你检查
other
是否不等于person
- 如果不等于,你调用你的相似度函数并将结果追加到
scores
中
你发布的构造被称为列表解析,它可以是一种很好的、简洁的、快速的书写方式,可以替代一系列普通的循环等。
编辑(感谢moooeeeep):