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
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']]]
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']]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With