environment: python 3.6.4
I have two list,
list1 is nested list of words, like
[['this', 'is', 'a', 'pen', 'that', 'is', 'a', 'desk'],
['this', 'is', 'an', 'apple']]
list2 is list of words to remove from list1 , like
['a', 'an']
I want to get new list like
[['this', 'is', 'pen', 'that', 'is', 'desk'],
['this', 'is', 'apple']]
and won't change list1.
I wrote below code, but my code destroy list1, where's wrong my code?
def remove_duplicate_element_in_nested_list(li1, li2):
"""
:param li1: <list> nested_sentences
:param li2: <list> words_to_remove
:return: <list>
"""
ret = []
for el1 in li1:
ret.append(el1)
for i in range(len(ret)):
for el2 in li2:
try:
# list.remove() remove only one element. so loop this.
for el in ret[i]:
ret[i].remove(el2)
except ValueError:
None
return ret
words = [['this', 'is', 'a', 'pen', 'this', 'is', 'a', 'desk'], ['this', 'is', 'an', 'apple']]
stop_words = ['a', 'an']
print(words)
# shows [['this', 'is', 'a', 'pen', 'that', 'is', 'a', 'desk'], ['this', 'is', 'an', 'apple']]
new_words = remove_duplicate_element_in_nested_list(words, stop_words)
print(words)
# shows [['this', 'is', 'pen', 'that', 'is', 'desk'], ['this', 'is', 'apple']]