首先,您应该将传入的字典和要返回的字典分开。
def build_person_to_matches(d, name):
ret = {}
collect = 0
for books in d[name]:
for person in d.keys():
if books in d[person]:
collect += 1
ret[person] = collect
return ret
d = {
'Tom': ['fiction', 'documentary', 'science'],
'John': ['computer science', 'math'],
'Jack': ['science', 'computer science', 'math', 'chemistry']
}
print build_person_to_matches(d, 'Jack')
其次,切换两个for循环的顺序,将collect = 0
行移到第一个循环中。
def build_person_to_matches(d, name):
ret = {}
for person in d.keys():
collect = 0
for books in d[name]:
if books in d[person]:
collect += 1
ret[person] = collect
return ret
d = {
'Tom': ['fiction', 'documentary', 'science'],
'John': ['computer science', 'math'],
'Jack': ['science', 'computer science', 'math', 'chemistry']
}
print build_person_to_matches(d, 'Jack')
可选地,为了可读性,您也可以将内部循环移到它自己的函数中,以使读者更清楚地了解正在发生的事情。
def how_many_genres_both_people_like(d, person_a, person_b):
total = 0
for books in d[person_a]:
if books in d[person_b]:
total += 1
return total
def build_person_to_matches(d, name):
ret = {}
for person in d.keys():
ret[person] = how_many_genres_both_people_like(d, name, person)
return ret
d = {
'Tom': ['fiction', 'documentary', 'science'],
'John': ['computer science', 'math'],
'Jack': ['science', 'computer science', 'math', 'chemistry']
}
print build_person_to_matches(d, 'Jack')
输出:
{'John': 2, 'Jack': 4, 'Tom': 1}