环境: 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']]
不会改变列表1。你知道吗
我写了下面的代码,但是我的代码破坏了列表1,我的代码哪里错了?你知道吗
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)
基本上现在
li1
和ret
都包含相同的内部列表。所以当你做ret[i].remove(el2)
的时候,它会把它从li1
和ret
中移除。你知道吗通过将行
ret.append(el1)
更改为ret.append(list(el1))
,可以使代码正常工作因为在python中一切都是对象,列表是可变的。 易于测试:
复制.deepcopy是一个建议
ret.append(el1)
不会复制内部列表,而是将引用复制到内部列表。你知道吗尝试使用
ret.append(el1[:])
,它使用slice操作符来创建副本。创建列表副本的其他方法如下所示:How to clone or copy a list?相关问题 更多 >
编程相关推荐