如何使2个“朋友”进行比较,并查看他们是否在彼此的朋友列表中?

2024-06-25 22:55:23 发布

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

因此,我使用类和def使之成为这样,如果两个人(我作为一个类)在彼此的朋友列表中,那么他们的ID是特定于每个人的。从该列表中删除,并添加到共同的朋友列表中

我没怎么试过,我一直在比较这两张单子

class People:

    '''People to make friendships, have a name, and a unique ID'''

    numsTimes = 0           ###Class variable for ID

    def __init__(self, name="anon"):
        if name == "anon": self.myname = makeRName()   ####Random Name
        else: self.myname = name
        self.friends = [] 
        self.mutualf = [] 

        self.ID = People.numsTimes          ###Unique ID
        People.numsTimes += 1

    def addFriend(self):            ###Ability for people to add others as friends
        self.friends.append(People.ID)

    def addMutual(self):
        ################I am looking for some if statement here.
        ###############Somehow remove others ID from both lists        
        self.mutualf.append(People.ID)
        else: return

我希望它会检查彼此的朋友名单,如果他们是朋友,他们将被添加到彼此的共同名单,并从朋友名单删除


Tags: tonameselfid列表forifdef
1条回答
网友
1楼 · 发布于 2024-06-25 22:55:23

如果我是你,我会用集合而不是列表来表示朋友。 你可以把共同的朋友比作:

class People:

    '''People to make friendships, have a name, and a unique ID'''

    numsTimes = 0           ###Class variable for ID

    def __init__(self, name="anon"):
        if name == "anon": self.myname = makeRName()   ####Random Name
        else: self.myname = name
        self.friends = {}
        self.mutualf = {} 

        self.ID = People.numsTimes          ###Unique ID
        People.numsTimes += 1

    def addMutual(self,other):
        mutual = self.friends.intersection(other.friends)
        self.mutual.add(mutual)
        self.friends.remove(mutual)

相关问题 更多 >