如果我有一个像这样的元组列表。
friendface = [('zeus','apollo'),('zeus','aphrodite'), ('apollo','aphrodite'), ('athena','hera'), ('hera','aphrodite'), ('aphrodite','apollo'), ('aphrodite','zeus'), ('athena','aphrodite'), ('aphrodite','athena'), ('zeus','athena'), ('zeus','hera')
我想编写一个名为 likes_relation(friendface)的函数,它返回一个字典,显示每个人的链接,解决方案看起来应该是这样的。
>>> likes_relation(friendface)
{'Aphrodite': ['Apollo', 'Zeus', 'Athena'],
'Hera': ['Aphrodite'],
'Zeus': ['Apollo', 'Aphrodite', 'Athena', 'Hera'],
'Apollo': ['Aphrodite'],
'Athena': ['Hera', 'Aphrodite'] }
如果有人知道如何做到这一点,我会很感激帮助,因为它现在真的开始烦我了。
谢谢!
编辑:我目前有一些可怕的代码。def likes_relation(friendface):
dict_friends = dict(friendface)
for name in friendface:
if name not in dict(friendface):
#dict(friendface)[name[:] = name[1]
#What i'm trying to do is go and run through the list
# again and if one of the sets isn't in the dictionary
# then add it.... obviously i don't know how...
返回dict(friendface)
答案 0 :(得分:1)
from collections import defaultdict
result = defaultdict(list)
map(lambda entry: result[entry[0]].append(entry[1]), friendface)