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']]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments