Imagine a social network website which allows people to specify which other people they like.
We can store information about who likes who in a list of tuples, such as the one assigned to
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’),
Write a Python function likes_relation(network) which takes a list of tuples as
its argument (in the format described above) and returns a dictionary as its result. The outputdictionary has strings for keys (representing names of people) and lists of strings for values (representing lists of names of people).
Each person in the dictionary is associated with the list of all and only the people that they like. For example, the function should behave like so when applied to the friendface list:
likes_relation(friendface)
{ 'Aphrodite': ['Apollo', 'Zeus', 'Athena'],
'Hera': ['Aphrodite'],
'Zeus': ['Apollo', 'Aphrodite', 'Athena', 'Hera'],
'Apollo': ['Aphrodite'],
'Athena': ['Hera', 'Aphrodite'] }
Sorry should add it's from a list of example exam questions but no answers are given.
I got as far as:
def likes_relations(network):
likes = {}
for k, v in network:
after than i am a bit lost as its not like any of the examples we did in class
解决方案
Use either defaultdict(list) or dict.setdefault(..., []) - there's not much difference in performance or readability, so it's really a matter of taste. I prefer using setdefault:
likes = {}
for k, v in friendface:
likes.setdefault(k, []).append(v)
社交网络喜欢关系解析
本文介绍了一种使用Python实现的方法,该方法通过处理元组列表来解析社交网络中的人际喜欢关系,并将其转换为易于理解的字典格式。具体而言,文章提供了一个名为likes_relation的函数,它接受一个包含姓名及其喜欢对象的元组列表作为输入,然后返回一个字典,该字典以姓名为键,值为他们喜欢的人的列表。
5410

被折叠的 条评论
为什么被折叠?



