10

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

3 Answers 3

9

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']]]
Sign up to request clarification or add additional context in comments.

Comments

2

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']]]

Comments

1

Based on a recipe found here:

def nested_list_replacer(seq, val = '-S', sub = ['not', 'letter']):
    def top_kill(s):
        for i in s:
            if isinstance(i, str):
                if i == val:
                    i = sub
                yield i
            else:                
                yield type(i)(top_kill(i))

    return type(seq)(top_kill(seq))        


l = ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
print(nested_list_replacer(l, '-S'))
print(nested_list_replacer(l, '-Q'))

Gives:

['and', ['or', ['not', 'letter'], 'Q'], ['or', ['not', 'letter'], 'R'], ['or', ['or', '-Q', '-R'], ['not', 'letter']]]
['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', ['not', 'letter'], '-R'], '-S']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.