将元组列表作为参数并返回字典作为结果

2024-04-26 10:55:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个这样的元组列表。你知道吗

friendface = [('zeus','apollo'),('zeus','aphrodite'), ('apollo','aphrodite'), ('athena','hera'), ('hera','aphrodite'), ('aphrodite','apollo'), ('aphrodite','zeus'), ('athena','aphrodite'), ('aphrodite','athena'), ('zeus','athena'), ('zeus','hera')

我想写一个名为likes\u 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)


Tags: nameindictlikesathenaherarelationapollo