在使用 any() 遍历时尝试使用删除重复项

Trying to use delete duplicates while using any() to go through the

我是学习 Python 的初学者,在使用任何(尝试学习 any()all())时试图从列表中删除重复项。

def remove_duplicates(x):
    l=0
    for i,item in enumerate(x):
        if any(l==item for l in x)==True:
            print (i,item)
            x=del x[i]
    return(x)
x=[1,2,3,1]
print (remove_duplicates(x))

我得到以下结果。

0 1
1 3
[2, 1]

而不是 [2,3,1]。

我知道您正在尝试学习 'any' 和 'all' 的用法,但是在遍历列表时移除或删除术语不是一个好主意。这是代码意外行为的原因。 但是,您可以使用集合来获取 list/tuple 中的现有项目而不重复。例如:

a = [0,1,3,1,0,3,4,6,4,5]
b = set(a)
print(b)

它returns:set([0,1,3,4,5,6)]

请注意 b 的类型是 'set'。如果你想让 b 变成 list 你可以使用:

b = list(set(a))

如果您不关心序列的顺序,只需执行:

list(set(x))