-4

d=字典

想要功能能够返回{'John':1,'Mark':3}

def build_person_to_matches(d, name): '''(dict of {str: list of str}, str) -> dict of {str: int}'''
    collect = 0
    for books in d[name]:
        for person in d.keys():
            if books in d[person]:
               collect += 1
        d[person] = collect
    return d

但该功能不适用于以下示例:

build_person_to_matches({'Tom': ['fiction', 'documentary', 'science'],'John': ['computer science', 'math'],'Jack': ['science', 'computer science', 'math', 'chemistry']}, 'Jack')
4

4 回答 4

1

首先,您应该将传入的字典和要返回的字典分开。

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}
于 2013-03-21T19:40:06.050 回答
0
for entry in d:
    print(entry + ':' + str(len(d[entry])))

(如果你把它放在一个函数中,用 return 替换 print )

它遍历字典“d”中的每个条目,然后找到相应条目的长度。只要确保将字典条目保持在您拥有的列表格式中,它应该可以解决!

于 2013-03-21T19:26:32.927 回答
0

使用字典推导和一些集合操作:

def build_person_to_matches(d, name):
    return {n:len(set(d[n]) & set(d[name])) for n in d}

或者,如果您不希望名称参数出现在匹配项中

def build_person_to_matches(d, name):
    return {n:len(set(d[n]) & set(d[name])) for n in d if n != name}

如果你不喜欢使用“&”来设置交集,你可以更具描述性

def build_person_to_matches(d, name):
    return {n:len(set(d[n]).intersection(d[name])) for n in d if n != name}
于 2013-03-21T20:06:45.373 回答
0

for books in d[name]:您可能希望在每个循环开始时重置收集值

于 2013-03-21T19:36:07.163 回答