发布网友 发布时间:2022-04-21 00:08
共1个回答
热心网友 时间:2022-04-06 15:47
1、使用set函数
set是定义集合的,无序,非重复
numList = [1,1,2,3,4,5,4]
print(list(set(numList)))
#[1, 2, 3, 4, 5]
2、先把list重新排序,然后从list的最后开始扫描
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]
3、使用字典函数
a=[1,2,4,2,4,]
b={}
b=b.fromkeys(a)
c=list(b.keys())
print(c) #[1, 2, 4]
4、append方式
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]
5、count + remove方式
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]