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)