随机生成列表:

import random
random.seed(1)
a=[]
for i in range(random.randint(10,20)):
    a.append(random.randint(0,10))
print('a =',a)

结果如下:

a = [9, 1, 4, 1, 7, 7, 7, 10, 6, 3, 1, 7]

以下方法大多来源于网络,并有少许增补

1.方法一

a1=list(set(a))
print('a1 =',a1)

2.方法二

import numpy as np
a2=list(np.unique(a))
print('a2 =',a2)

3.方法三

a3=sorted(a)
[a3.remove(a3[i]) for i in range(len(a3)-1,-1,-1) if a3[i]==a3[i-1]]
print('a3 =',a3)

4.方法四

a4=sorted(a)
a4=[e for i,e in enumerate(a4) if e not in a4[:i]]
print('a4 =',a4)

5.方法五

a5=a.copy()
[a5.remove(i) for i in a5[::-1] if a5.count(i)>1]
print('a5 =',a5)

6.方法六

a6=[]
[a6.append(i) for i in a if i not in a6]
print('a6 =',a6)

7.方法七

from collections import Counter
a7=list(Counter(a).keys())
print('a7 =',a7)

8.方法八

a8=list({}.fromkeys(a).keys())
print('a8 =',a8)

9.方法九

a9=sorted(set(a),key=a.index)
print('a9 =',a9)

10.方法十

a10=a.copy()
[a10.pop(i) for i in range(len(a10)-1,-1,-1) if a10.count(a10[i])>1]
print('a10 =',a10)

综上结果如下:

a = [9, 1, 4, 1, 7, 7, 7, 10, 6, 3, 1, 7] #原列表
a1 = [1, 3, 4, 6, 7, 9, 10]
a2 = [1, 3, 4, 6, 7, 9, 10]
a3 = [1, 3, 4, 6, 7, 9, 10]
a4 = [1, 3, 4, 6, 7, 9, 10]
a5 = [9, 4, 10, 6, 3, 1, 7]
a6 = [9, 1, 4, 7, 10, 6, 3]
a7 = [9, 1, 4, 7, 10, 6, 3]
a8 = [9, 1, 4, 7, 10, 6, 3]
a9 = [9, 1, 4, 7, 10, 6, 3]
a10 = [9, 1, 4, 7, 10, 6, 3]
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐