如果我有这样的元组列表的话。
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...回敬(朋友)
发布于 2013-11-10 04:26:50
from collections import defaultdict
result = defaultdict(list)
map(lambda entry: result[entry[0]].append(entry[1]), friendface)https://stackoverflow.com/questions/19886201
复制相似问题