如何在python3中删除列表中的重复元素?

2024-05-07 00:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

环境: 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']]

Tags: 代码inanapple列表forthatis
3条回答

代码中的问题在于这一行

ret.append(el1)

基本上现在li1ret都包含相同的内部列表。所以当你做ret[i].remove(el2)的时候,它会把它从li1ret中移除。你知道吗

通过将行ret.append(el1)更改为ret.append(list(el1)),可以使代码正常工作

因为在python中一切都是对象,列表是可变的。 易于测试:

>>> lst = [[1], [2]]
>>> new_lst = []
>>> for e in lst:
...     new_lst.append(e)
...
>>> new_lst[0] is lst[0]
True
>>> new_lst[0].append(10)
>>> new_lst
[[1, 10], [2]]
>>> lst
[[1, 10], [2]]

复制.deepcopy是一个建议

ret.append(el1)不会复制内部列表,而是将引用复制到内部列表。你知道吗

尝试使用ret.append(el1[:]),它使用slice操作符来创建副本。创建列表副本的其他方法如下所示:How to clone or copy a list?

相关问题 更多 >