假设我有以下数据结构
input = ["the","elephant","sneezed"]
g = {'S': [['VP', 'NP']], 'NP': [['N', 'DET']], 'N': [['elephant']], 'DET':[["the"]]}
stack = [['VP','N','the']]
现在如何比较输入 (the) 中的第一个元素与堆栈中的最后一个元素以查看是否匹配?如果匹配,从每个列表中删除两个元素?
if input[0] == stack[-1]:
i = input.pop()
s = stack.pop()
print(i)
print(s)
所需的输出:
input=["elephant","sneezed"]
stack=[["VP","N"]
答案 0 :(得分:2)
首先,由于 stack 是一个列表列表,所以在比较时必须使用 stack[0][-1] 而不是 stack[-1](基本上是 stack 第一个元素的最后一个元素)。默认情况下 pop() 删除列表的最后一个元素。由于我们要删除 input 的第一个元素,因此我们必须提供要删除的索引 0,即 input.pop(0)。
input = ["the","elephant","sneezed"]
g = {'S': [['VP', 'NP']], 'NP': [['N', 'DET']], 'N': [['elephant']], 'DET':[["the"]]}
stack = [['VP','N','the']]
if input[0] == stack[0][-1]:
i = input.pop(0)
s = stack[0].pop()
print(i)
print(s)