删除 python 列表中的选定重复项

Removing selected duplicates in a python list

假设我有以下列表:

my_list = ["sam","sam", "is", "a", "is", "sam" , "good", "person", "person"]

现在我的要求是编写一个有选择地删除重复项的函数。我想在 for 循环中使用这个函数。

假设我想删除“sam”重复项

这意味着在第一次迭代后我想要的结果如下:

my_list  = ["sam", "is", "a", "is", "good", "person", "person"]

仅删除“sam”的重复项。

类似地,在第二次迭代之后,我要删除的是“person”,因此我的列表将如下所示:

 my_list  = ["sam", "is", "a", "is", "good", "person"]

请建议我可以做到这一点的方法?

感谢和问候

我认为最干净的方法是使用列表理解删除元素的所有外观,然后将元素添加到末尾。 你可以这样做:

def removeDuplicates(my_list,current):
    return [ element for element in my_list if element != current] + [current]

并调用函数:

>>> my_list
['sam', 'sam', 'is', 'a', 'is', 'sam', 'good', 'person', 'person']

>>> my_list2 = removeDuplicates(my_list,"sam")
>>> my_list2
['is', 'a', 'is', 'good', 'person', 'person', 'sam']

>>> my_list3 = removeDuplicates(my_list2,"person")
>>> my_list3
['is', 'a', 'is', 'good', 'sam', 'person']

试试这个,

def remove(key, value):
    filter_ = []
    for v in value:
        if key == v and key in filter_:
            continue

        filter_.append(v)
    return filter_


my_list = ["sam","sam", "is", "a", "is", "sam" , "good", "person", "person"]

my_list = remove("sam", my_list)
print(my_list)

my_list = remove("person", my_list)
print(my_list)

['sam', 'is', 'a', 'is', 'good', 'person', 'person']

['sam', 'is', 'a', 'is', 'good', 'person']

对于选择性的东西,你需要遍历列表:

def remove_duplicate_selection(my_list, item):
    flag = False
    length = len(my_list)
    for i in range(length):
        if length == i:
            break
        if my_list[i] == item:
            if flag:
                del my_list[i]
                length -= 1
            else:
                flag = True
    return my_list


def main():
    my_list = ["sam", "sam", "is", "a", "is", "sam", "good", "person", "person"]
    remove_duplicate_selection(my_list, "sam")
    print(my_list)
    remove_duplicate_selection(my_list, "person")
    print(my_list)


if __name__ == '__main__':
    main()

输出应该是:

['sam', 'is', 'a', 'is', 'good', 'person', 'person']
['sam', 'is', 'a', 'is', 'good', 'person']