1
我使用Python来实现的厄雷分析器已定义上下文无关规则如下:如何检查对象列表中是否存在对象?
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
要检查Rule
类的对象是否一个图表阵列内的存在与否,我已经使用了以下内容:
def enqueue(self, entry, state):
if state in self.chart[entry]:
return None
else:
self.chart[entry].append(state)
其中图表是应该包含Rule
类的对象的列表的数组:
def __init__(self, words):
self.chart = [[] for i in range(len(words))]
而且我检查规则是否为存在于chart[entry]
如下(如果它不存在,那么只需追加):
def enqueue(self, entry, state):
if state in self.chart[entry]:
return None
else:
self.chart[entry].append(state)
但是这给了我一个错误
TypeError: 'in <string>' requires string as left operand, not classobj
要为了避免这种情况,我甚至在课堂上宣布了__eq__
函数,但它似乎不起作用。任何人都可以帮助我一样吗?
你是否100%确定'self.chart [entry]'是一个列表?从错误消息看来,'self.chart [entry]'是一个字符串。 'enqueue'开始时如果你使用'print type(self.chart [entry])'显示什么? – Kevin
将'class rule:'更改为'class Rule(object):' – Daenyth
@所有,编辑上面的代码。 – AbbaShareen