I have a problem in python and one step I need to do is to access the second element of every list in a list of lists. The list is:
[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')] [(0, 'A', 'DET' 'det'), (1 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]
The list goes on like that with different sentences for each list.
What I am trying to do is access the third (index 2) element of every list of every tuple. So from the first list, I want to get:
- PROPN (from ‘Gallery’)
- VERB (from ‘unveils’)
- ADJ (from ‘interactive’)
And from the second list I want to get:
- DET (from ‘A’)
- PROPN (from ‘Christmas’)
- NOUN (from ‘nsubjpass)
What I’ve tried to do is this:
for word in list: print(list[word])
But that only outputs the second element from the first list. I tried creating another foor-loop but that didn’t work, I suspect I did it wrong but I’m not sure how to solve it
Help would be appreciated
Thanks in advance!
when you are enumerating over the list in the for loop:
for word in words: pass // do something
You have already accessed the element in the list and stored it in
word in your loop would be accessing the first element in your word tuple which is not what you’d like to do.
Instead, you’d like to access
word in your tuple, so something like this should work:
first_list = [(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')] second_list = [(0, 'A', 'DET' 'det'), (1, 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')] def print_word_pos(words): for word in words: print(word) print_word_pos(first_list) print_word_pos(second_list)
Another thing is that you should not be naming your lists as
list is a reserved python keyword and might (will) cause conflict later down the line.
Now if the first two lists were combined, you’d want to loop over each list and then for each word in that list, print out the part of speech.
def print_word_pos(list_of_words): for words in list_of_words: for word in words: print(word)