首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将元组列表作为参数,然后返回字典。

将元组列表作为参数,然后返回字典。
EN

Stack Overflow用户
提问于 2013-11-10 04:16:21
回答 1查看 52关注 0票数 0

如果我有这样的元组列表的话。

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)的函数,它返回一个字典,它显示每个人的链接,解决方案应该是这样的。

代码语言:javascript
复制
>>> likes_relation(friendface)

{'Aphrodite': ['Apollo', 'Zeus', 'Athena'],
'Hera': ['Aphrodite'],
'Zeus': ['Apollo', 'Aphrodite', 'Athena', 'Hera'],
'Apollo': ['Aphrodite'],
'Athena': ['Hera', 'Aphrodite'] }

如果有人知道该怎么做的话,我会感谢你的帮助,因为它现在真的开始让我恼火了。

谢谢!

编辑:我现在有一些可怕的代码。

代码语言:javascript
复制
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...

回敬(朋友)

EN

回答 1

Stack Overflow用户

发布于 2013-11-10 04:26:50

代码语言:javascript
复制
from collections import defaultdict
result = defaultdict(list)
map(lambda entry: result[entry[0]].append(entry[1]), friendface)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19886201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档