我正在尝试设置一个函数来计算两部电影的相似度。有预先存在的词典,以电影为关键,导演,流派或主要演员都是价值观。有三个演员词典(每部电影的3个主要演员列出)。代码大多数工作正常,但有时我得到的分数大于我应该得到的分数。
# create a two-variable function to deterime the FavActor Similarity score:
def FavActorFunction(film1,film2):
#set the result of the FavActor formula between two films to a default of 0.
FavActorScore = 0
#add 3 to the similarity score if the films have the same director.
if direct[film1] == direct[film2]:
FavActorScore += 3
#add 2 to the similarity score if the films are in the same genre.
if genre[film1] == genre[film2]:
FavActorScore += 2
#add 5 to the similarity score for each actor they have in common.
if actor1[film1] == actor1[film2] or actor2[film2] or actor3[film2]:
FavActorScore += 5
if actor2[film1] == actor1[film2] or actor2[film2] or actor3[film2]:
FavActorScore += 5
if actor3[film1] == actor1[film2] or actor2[film2] or actor3[film2]:
FavActorScore += 5
#print the resulting score.
return FavActorScore
我的假设是,在计算他们共同的演员时,它会计算两次事情。有没有办法修改这部分代码,以便得到更准确的结果?
if actor1[film1] == actor1[film2] or actor2[film2] or actor3[film2]:
FavActorScore += 5
if actor2[film1] == actor1[film2] or actor2[film2] or actor3[film2]:
FavActorScore += 5
if actor3[film1] == actor1[film2] or actor2[film2] or actor3[film2]:
FavActorScore += 5
答案 0 :(得分:1)
尝试使用in
条件:
if actor1[film1] in (actor1[film2], actor2[film2], actor3[film2]):
FavActorScore += 5
if actor2[film1] in ( actor1[film2], actor2[film2], actor3[film2]):
FavActorScore += 5
if actor3[film1] in (actor1[film2], actor2[film2], actor3[film2]):
FavActorScore += 5
当你写a==b or c or d
时,如果a等于b或者c为真,或者d为真,则如果a等于b或c或d则为真。