【问题标题】:How to make 2 "Friends" compare and see if they are on eachothers list of friends?如何让 2 个“朋友”比较,看看他们是否在彼此的朋友列表中?
【发布时间】:2019-07-11 03:56:37
【问题描述】:

所以我使用类和 def 来制作它,所以如果 2 个人(我作为一个类)在彼此的朋友列表中,那么他们的 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

我希望它会检查彼此的朋友列表,如果他们是彼此的朋友,他们将被添加到彼此的相互列表中并从朋友列表中删除。

【问题讨论】:

  • 我没有看到你在addMutual传递其他ID
  • 是的,我有点卡住了。我在随机造人,所以我很难考虑如何比较两个不存在的人名单,哈哈。
  • 简单地说,你需要两个 id 和两个朋友列表来实现你想要的

标签: python list class default


【解决方案1】:

如果我是你,我会使用集合而不是朋友列表。 您可以将共同的朋友与:

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)

【讨论】:

  • 啊,谢谢。我是 python 新手,所以我什至不知道 .intersection。非常感谢!
猜你喜欢
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 2011-08-10
  • 2012-02-12
  • 1970-01-01
相关资源
最近更新 更多