环境:python 3.6.4
我有两个列表,
list1是嵌套的单词列表,就像
[['this', 'is', 'a', 'pen', 'that', 'is', 'a', 'desk'],
['this', 'is', 'an', 'apple']]
list2是要从list1中删除的单词列表,例如
['a', 'an']
我想获得新的清单,例如
[['this', 'is', 'pen', 'that', 'is', 'desk'],
['this', 'is', 'apple']]
并且不会更改list1。
我在下面的代码中编写了代码,但是我的代码破坏了list1,我的代码哪里错了?
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']]
ret.append(el1)
不会复制内部列表,而是将引用复制到内部列表。
尝试使用ret.append(el1[:])
哪个使用slice运算符来创建副本。创建清单副本的其他方法如下所示:如何克隆或复制清单?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句