对于存储多个键和值字典的结构,最好的建议是什么?

2024-05-16 22:28:16 发布

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

其目的是创建一个facebook类型的程序(用于教学目的)的开端,该程序存储一个个人名单以及他们的个人信息。你知道吗

我有两个问题,一个接一个:

问题1:如何获取列表值,这些值是字典中键值对中值的一部分。例如,要找出约翰和玛丽有哪些共同的朋友,在本例中,朋友1和朋友3

问题2:创建存储姓名、性别、爱好和朋友的结构的最佳方法是什么?这是一本字典吗?如果是的话,这是怎么定义的?如果没有,人们有什么建议?你知道吗

#create a dictionary that stores names, and a list of friends
facebook_profile={"John":["friend1","friend2","friend3","friend4"],"Mary":["friend1","friend7","friend3","friend9"]}
print(facebook_profile)

需要存储并随后打印以下样本数据:

Name:John
Gender: Male
Hobbies: Chess
Friends: friend1,friend2,friend3,friend4

Name: Mary
Gender: Female
Hobbies: Chequers
Friends: friend1,friend2,friend3,friend4    

我知道最好的解决方案是建立一个数据库,并使用某种文件处理来实现它。然而,出于教学目的,我们只尝试使用列表或字典。这些字典/列表可以被写入一个文件,但我要寻找的解决方案/答案在理想情况下只能使用列表和字典结构。你知道吗


Tags: 程序目的列表facebook字典朋友profilejohn
3条回答

对于问题1,集合是快速方便地计算交点的好选择。 对于问题2,一本字典很管用。你知道吗

例如:

facebook_profile={
    "John":{"friends":{"friend1","friend2","friend3","friend4"},"Gender": "Male"},
    "Mary":{"friends":{"friend1","friend7","friend3","friend9"},"Gender": "Female"}
}
mutual_friends = facebook_profile["John"]["friends"].intersection(facebook_profile["Mary"]["friends"])
print (mutual_friends)

提供输出:

{'friend1', 'friend3'}

创建类:

class Person:

  def __init__(self, name, gender, hobbies, friends):
    self.name = name
    self.gender = gender
    self.hobbies = hobbies
    self.friends = friends

  def getMutualFriends(self, personB):
    return list(set(personB.friends).intersection(self.friends))

person1 = Person('John', 'male', ['Chess'], ['friend1', 'friend2'])
person2 = Person('Anna', 'female', ['Soccer'], ['friend1', 'friend3'])

print(person1.getMutualFriends(person2))

另一种方法是在数据库中存储与该表具有多对多关系的表列和firends。你知道吗

相关问题 更多 >