Python 如何检查对象列表中是否存在对象?
我正在使用Python实现Earley解析器,该解析器具有定义如下的上下文无关规则:Python 如何检查对象列表中是否存在对象?,python,list,class,object,Python,List,Class,Object,我正在使用Python实现Earley解析器,该解析器具有定义如下的上下文无关规则: 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 = s
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
class YourObject:
[...]
def __eq__(self, other):
return self.title == other.title
为了检查图表数组中是否存在规则
类的对象,我使用了以下方法:
def enqueue(self, entry, state):
if state in self.chart[entry]:
return None
else:
self.chart[entry].append(state)
其中,图表是一个数组,它应该包含类规则的对象列表:
def __init__(self, words):
self.chart = [[] for i in range(len(words))]
此外,我检查是否存在如下图表[entry]
中的规则(如果不存在,则只需追加):
然而,这给了我一个错误
TypeError: 'in <string>' requires string as left operand, not classobj
TypeError:'in'需要字符串作为左操作数,而不是classobj
为了避免这种情况,我甚至在类本身中声明了一个\uuuuueq\uuuu
函数,但它似乎不起作用。有人能帮我做同样的事情吗?假设您的对象只有一个与相等性相关的title属性,您必须实现\uuuuuueq\uuuuu
方法,如下所示:
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
class YourObject:
[...]
def __eq__(self, other):
return self.title == other.title
当然,如果您有更多与平等相关的属性,那么也必须包括这些属性。您也可以考虑执行代码> > NoSux和Y.CMPAX一致的行为。 < P>假设您的对象只有一个与平等相关的标题属性,则必须执行<代码>
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
class YourObject:
[...]
def __eq__(self, other):
return self.title == other.title
当然,如果您有更多与平等相关的属性,那么也必须包括这些属性。您也可以考虑执行代码> > NoSux和 > CMPAX<<代码>一致性行为。您是否确信“代码>自已?图表[条目] < /代码>是一个列表?从错误消息看,似乎self.chart[entry]
是一个字符串。如果您在排队
的开头执行打印类型(self.chart[entry])
会显示什么?将类规则:
更改为类规则(对象):
@All,编辑上面的代码。@Kevin它说类型是否100%确定self.chart[entry]
是一个列表?从错误消息看,似乎self.chart[entry]
是一个字符串。如果您在排队
的开头执行打印类型(self.chart[entry])
,会显示什么?将类规则:
更改为类规则(对象):
@All,编辑上面的代码。@Kevin上面写的是类型