Creating a list of lists after accessing a tuple

Question:

I am trying to create a nested list after accessing the first element of a tuple in a nested list. Below is the sample input.

nested = [
         [('wow', 'NN'), ('loved', 'VBD'), ('place', 'NN')],
         [('great', 'JJ'), ('touch', 'NN')]
         ]

Below is the sample code for use

mapped_pos = {
    # Nouns
    'NN':wordnet.NOUN,
    # Verbs
    'VB':wordnet.VERB,
    # Adjectives
    'JJ':wordnet.ADJ,
    # Adverbs
    'RB':wordnet.ADV,}

normalised_sequence = []
for i in nested:
    for tuples in i:
        temp = tuples[0]
        if tuples[1] == "NNP" or tuples[1] =="NNPS":
            continue
        elif tuples[1][:2] in mapped_pos.keys():
            temp = lemmaword.lemmatize(tuples[0],pos=mapped_pos[tuples[1][:2]])
            x = ''.join(temp)
            normalised_sequence.append(x)

print(f"nLemmatised words:n{normalised_sequence}")

Below is the given output

Lemmatised words:
['wow', 'love', 'place', 'great', 'touch']

The expected output should be this as shown below;

[['wow', 'love', 'place'], ['great', 'touch']]

Which then permits a final outcome of the following below when supplied any given list as input;

[
'wow love place', 
'great touch'
]
Asked By: Daniel Ihenacho

||

Answers:

You append individual values to normalised_sequence, but you want to add sublists. Try this:

normalised_sequence = []
for i in nested:
    sublist = []

    for tuples in i:
        temp = tuples[0]
        if tuples[1] == "NNP" or tuples[1] =="NNPS":
            continue
        elif tuples[1][:2] in mapped_pos.keys():
            temp = lemmaword.lemmatize(tuples[0],pos=mapped_pos[tuples[1][:2]])
            x = ''.join(temp)
            sublist.append(x)
    normalised_sequence.append(sublist) # or normalised_sequence.append(' '.join(sublist)) is you want to merge the items to strings
Answered By: RJ Adriaansen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.