简体   繁体   中英

How to match elements in a list with elements in a list of lists

Suupose I have the following data structure

input = ["the","elephant","sneezed"]
g = {'S': [['VP', 'NP']], 'NP': [['N', 'DET']], 'N': [['elephant']], 'DET':[["the"]]}
stack = [['VP','N','the']]

How can I now compare the first element in input (the) with the last element in stack to see if there is a match? And if there is a match, remove both elements out of each list?

if input[0] == stack[-1]:
    i = input.pop()
    s = stack.pop()
    print(i)
    print(s)

Desired output:

input=["elephant","sneezed"]
stack=[["VP","N"]

First of all, since stack is a list of lists, you have to use stack[0][-1] instead of stack[-1] while comparing (Basically, the last element of the first element of stack). By default pop() removes the last element of a list. Since we are removing the first element of input, we have to provide the index to remove which is 0 ie, 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)

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