想象一下,一个允许人们指定他们喜欢的其他人的社交网络网站。
我们可以将关于谁喜欢谁的信息存储在元组列表中,比如分配给
friendface below:
friendface = [
(’Zeus’,’Apollo’),
(’Zeus’,’Aphrodite’),
(’Apollo’,’Aphrodite’),
(’Athena’,’Hera’),
(’Hera’,’Aphrodite’),
(’Aphrodite’,’Apollo’),
(’Aphrodite’,’Zeus’),
(’Athena’,’Aphrodite’),
(’Aphrodite’,’Athena’),
(’Zeus’,’Athena’),
(’Zeus’,’Hera’),编写一个Python函数likes_relation(network),它将元组列表作为其参数(采用上述格式),并返回一个字典作为其结果。输出字典包含键字符串(表示人名)和字符串列表(表示人名列表)。
字典中的每个人都与所有且仅与他们喜欢的人的列表相关联。例如,该函数在应用于friendface列表时应如下所示:
likes_relation(friendface)
{ 'Aphrodite': ['Apollo', 'Zeus', 'Athena'],
'Hera': ['Aphrodite'],
'Zeus': ['Apollo', 'Aphrodite', 'Athena', 'Hera'],
'Apollo': ['Aphrodite'],
'Athena': ['Hera', 'Aphrodite'] }对不起,应该添加它是从一个示例试题列表中,但没有给出答案。我得到的结果是: def likes_relations(网络):
likes = {} for k, v in network:看完之后,我有点迷茫,因为它不像我们在课堂上做过的任何例子
发布于 2013-11-08 16:27:28
使用defaultdict(list)或dict.setdefault(..., []) -在性能或可读性上没有太大差异,所以这实际上是一个品味问题。我更喜欢使用setdefault
likes = {}
for k, v in friendface:
likes.setdefault(k, []).append(v)发布于 2013-11-08 16:46:03
这是一个使用defaultdict的解决方案
def likes_relation(friendface):
d = defaultdict(list)
for k, v in friendface:
d[k].append(v)
return d结果:
>>> for k,v in likes_relation(f).items():
print (k, v)
Hera ['Aphrodite']
Apollo ['Aphrodite']
Aphrodite ['Apollo', 'Zeus', 'Athena']
Zeus ['Apollo', 'Aphrodite', 'Athena', 'Hera']
Athena ['Hera', 'Aphrodite']希望这能有所帮助!
https://stackoverflow.com/questions/19854442
复制相似问题