Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Iterate over each item in nested-list-of-lists and replace specific items

I am a beginner in python. I want to know if there is any in-built function or other way so I can achieve below in python 2.7:

Find all -letter in list and sublist and replace it with ['not',letter]

Eg: Find all items in below list starting with - and replace them with ['not',letter]

Input : ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
Output : ['and', ['or', ['not','S'], 'Q'], ['or', ['not','S'], 'R'], ['or', ['or', ['not','Q'], ['not','R']], ['not','S']]]

Can anyone suggest how to do it in python. Thanks

like image 650
skool99 Avatar asked Mar 20 '15 04:03

skool99


2 Answers

Try a bit of recursion:

def change(lol):
    for index,item in enumerate(lol):
        if isinstance(item, list):
            change(item)
        elif item.startswith('-'):
            lol[index] = ['not',item.split('-')[1]]
    return lol

In action:

In [24]: change(['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']])
Out[24]:
['and',
['or', ['not', 'S'], 'Q'],
['or', ['not', 'S'], 'R'],
['or', ['or', ['not', 'Q'], ['not', 'R']], ['not', 'S']]]
like image 88
salparadise Avatar answered Oct 11 '22 12:10

salparadise


You need to use a recursive function.The isinstance(item, str) simply checks to see if an item is string.

def dumb_replace(lst):
     for ind, item in enumerate(lst):
         if isinstance(item, str):
             if item.startswith('-'):
                 lst[ind] = ['not', 'letter']
         else:
             dumb_replace(item)

And:

dumb_replace(Input)

Gives:

['and', ['or', ['not', 'letter'], 'Q'], ['or', ['not', 'letter'], 'R'], ['or', ['or', ['not', 'letter'], ['not', 'letter']], ['not', 'letter']]]
like image 33
styvane Avatar answered Oct 11 '22 13:10

styvane