简体   繁体   中英

How to check if an object exists inside a list of objects?

I am using Python to implement an Earley Parser that has Context Free rules defined as follows:

class Rule:
    def __init__(self,string,i,j,dot):
        self.i = 0
        self.j = 0
        self.dot = 0
        string = string.split('->')
        self.lhs = string[0].strip()
        self.rhs1 = string[1].strip()
        self.rhs = []
        self.rhs1 = self.rhs1.split(' ')
        for word in self.rhs1:
            if word.strip()!= '':
                self.rhs.append(word)

    def __eq__(self, other):
        if self.i == other.i:
            if self.j == other.j:
                if self.dot == other.dot:
                    if self.lhs == other.lhs:
                        if self.rhs == other.rhs:
                            return True
        return False

To check whether an object of class Rule exists within a chart array or not, I have used the following:

def enqueue(self, entry, state):
    if state in self.chart[entry]:
        return None
    else:
        self.chart[entry].append(state)

where chart is an array that is supposed to contain lists of objects of class Rule :

def __init__(self, words):
    self.chart = [[] for i in range(len(words))]

Further I check whether a rule exists as that in the chart[entry] as follows (and if it does not exist, then simply append):

def enqueue(self, entry, state):
    if state in self.chart[entry]:
        return None
    else:
        self.chart[entry].append(state)

However this gives me an error as

TypeError: 'in <string>' requires string as left operand, not classobj

To circumvent this, I even declared an __eq__ function in the class itself but it doesn't seem to work. Can anyone help me with the same?

Assuming that your object has only a title attribute which is relevant for equality, you have to implement the __eq__ method as follows:

class YourObject:
    [...]
    def __eq__(self, other):
        return self.title == other.title

Of course if you have more attributes that are relevant for equality, you must include those as well. You might also consider implementing __ne__ and __cmp__ for consistent behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM