Search code examples
pythonlistnestednested-loops

operations with nested lists in python


I'm trying to iterate through a nested list and make some changes to the elements. After changing them I'd like to save results in the same nested list. For example, I have

text = [['I', 'have', 'a', 'cat'], ['this', 'cat', 'is', 'black'], ['such', 'a', 'nice', 'cat']]

I want to get a list of lists with elements slightly changed. For example:

text = [['I_S', 'have', 'a_A', 'cat'], ['this', 'cat_S', 'is', 'black_A'], ['such', 'a', 'nice', 'cat_S']]

Firstly, I go through each list, then go through each item in a list and then apply additional code to make changes needed. But how to return the nested list back after operations? This is what I do:

for tx in text:
    for t in tx:
        #making some operations with each element in the nested list.
        #using if-statements here
    result.append()

And what I've got the single list with all the changed elements from the nested list

result = ['I_S', 'have', 'a_A', 'cat', 'this', 'cat_S', 'is', 'black_A', 'such', 'a', 'nice', 'cat_S']

I need to keep the nested list because it's actually the sentences from the text.


Solution

  • To create a nested list as output try this:

    result = []
    for i in range(len(text)):
        temp = []
        for t in text[i]:
            word_modified = t
            #making some operations with each element in the nested list.
            #using if-statements here
            temp.append(word_modified)
        result.append(temp)
    result
    

    If you just copy paste this code, result will be the equal to text. But as in the loop t represents each word separatly, you should be able to modifiy it as you wish.