在字典中,找到具有最多共同值的键

时间:2019-06-21 15:44:50

标签: python loops dictionary nested

我不知道从哪里开始。给出了以下说明:

查找拥有最多共同电影的演员。输出所有关系。 解决方案使用name_and_movies词典,该词典将每个人与他/她所参与的电影集相关联。然后,您将需要double for循环。通过智能地终止循环,可以使其变得更快。如果找到了共有k个电影的演员,则无需考虑少于k个电影的演员。

这是name_and_movies词典。

{'Kishiro, Yukito': {'Battle Angel'}, 
'Wilson, Owen': {'The Internship', 
'Midnight in Paris', 'Wedding Crashers'}, 
'Vaughn, Vince': {'Made', 'Swingers', 
'The Internship', 'Wedding Crashers'}, 
'Favreau, Jon': {'Made', 'Swingers'}, 
'Jackman, Hugh': {'The Greatest Showman', 'X-Men'}, 
'Roth, Tim': {'Planet of the Apes'}, 
'Cooper, Chris': {'Capote'}, 
'Wilson, Luke': {'Rushmore'}, 
'Vaughn, Robert': {'The Statue'}, 
'Graham, Heather': {'Swingers'}}

预期输出:

文斯·沃恩和欧文·威尔逊有2部共同的电影。

Vince Vaughn和Jon Favreau有2部共同的电影。

1 个答案:

答案 0 :(得分:0)

您可以使用itertools中的combinations()来生成演员对并与他们的电影相交。然后选择交叉点最大的对:

films = {'Kishiro, Yukito': {'Battle Angel'}, 
'Wilson, Owen': {'The Internship', 
'Midnight in Paris', 'Wedding Crashers'}, 
'Vaughn, Vince': {'Made', 'Swingers', 
'The Internship', 'Wedding Crashers'}, 
'Favreau, Jon': {'Made', 'Swingers'}, 
'Jackman, Hugh': {'The Greatest Showman', 'X-Men'}, 
'Roth, Tim': {'Planet of the Apes'}, 
'Cooper, Chris': {'Capote'}, 
'Wilson, Luke': {'Rushmore'}, 
'Vaughn, Robert': {'The Statue'}, 
'Graham, Heather': {'Swingers'}}


from itertools import combinations
common    = [ (a1,a2,films[a1]&films[a2]) for a1,a2 in combinations(films,2) ]
maxCommon = max(len(c[2]) for c in common)
result    = [ (actor1,actor2) for actor1,actor2,films in common if len(films)==maxCommon ]
print(maxCommon,result)

# 2 [('Wilson, Owen', 'Vaughn, Vince'), ('Vaughn, Vince', 'Favreau, Jon')]

注意:输出是成对出现的,因此它并不表示Owen Wilson与Jon Favreau有2部相同的电影。

您可以添加电影交集以了解演员之间共有哪些电影:

result    = [ (actor1,actor2,films) for actor1,actor2,films in common if len(films)==maxCommon ]

# 2 [('Wilson, Owen', 'Vaughn, Vince', {'Wedding Crashers', 'The Internship'}), ('Vaughn, Vince', 'Favreau, Jon', {'Swingers', 'Made'})]

编辑 不使用列表推导(即使用循环),它对应于以下内容:

common    = list()
maxCommon = 0
actors    = list(films)
for i,actor1 in enumerate(actors[:-1]):
    for actor2 in actors[i+1:]:
        commonFilms = films[actor1] & films[actor2]
        common.append( (actor1,actor2,commonFilms) )
        maxCommon = max(len(commonFilms),maxCommon)
result = list()
for actor1,actor2,films in common:
    if len(films)==maxCommon:
        result.append((actor1,actor2))
print(maxCommon,result)