Skip to main content
 首页 » 编程设计

python之如何删除python3中列表中的重复元素

2024年09月07日15think

环境: 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) 不会复制内部列表,而是将 reference 复制到内部列表。

尝试使用 ret.append(el1[:]),它使用切片运算符来创建副本。此处说明了创建列表副本的其他方法:How to clone or copy a list?