回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>环境:
python 3.6.4版</p>
<p>我有两张单子,<br/>
list1是单词的嵌套列表,如</p>
<pre><code>[['this', 'is', 'a', 'pen', 'that', 'is', 'a', 'desk'],
['this', 'is', 'an', 'apple']]
</code></pre>
<p>list2是要从list1中删除的单词列表,如</p>
<pre><code>['a', 'an']
</code></pre>
<p>我想得到一份新的名单</p>
<pre><code>[['this', 'is', 'pen', 'that', 'is', 'desk'],
['this', 'is', 'apple']]
</code></pre>
<p>不会改变列表1。你知道吗</p>
<p>我写了下面的代码,但是我的代码破坏了列表1,我的代码哪里错了?你知道吗</p>
<pre><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']]
</code></pre>