Python删除list里的重复元素有几种方法

set是定义集合的,无序,非重复

numList = [1,1,2,3,4,5,4]
print(list(set(numList)))
#[1, 2, 3, 4, 5]

a = [1, 2, 4, 2, 4, 5,]
a.sort()
last = a[-1]
for i in range(len(a) - 2, -1, -1):
    if last == a[i]:
        del a[i]
    else:
        last = a[i]
print(a) #[1, 2, 4, 5]

a=[1,2,4,2,4,]

b={}

b=b.fromkeys(a)

c=list(b.keys())

print(c) #[1, 2, 4]

def delList(L):
    L1 = []
    for i in L:
        if i not in L1:
            L1.append(i)
    return L1
print(delList([1, 2, 2, 3, 3, 4, 5])) #[1, 2, 3, 4, 5]

def delList(L):
    for i in L:
        if L.count(i) != 1:
            for x in range((L.count(i) - 1)):
                L.remove(i)
    return L
print(delList([1, 2, 2, 3, 3, 4]))#[1, 2, 3, 4]

随机文章