方法一:使用集合set;将list直接转换为set
1 a = [1,3,4,3,5,7] 2 a = list(set(a)) 3 print(a)
执行结果:
[1, 3, 4, 5, 7]
方法二:直接排序,然后逐个比较,鉴于del会直接把元素删除,设置个flag数组来编辑该删除的元素(这个思路是看人家这么写的,有点麻烦,但是也是可以实现的,设置了标志位)1 namelist = ['Marry','Andy','Carol','Jack','Marry','Hanmeimei','Andy'] 2 namelist.sort() 3 flag = [] 4 for i in range(len(namelist)): 5 flag.append(0) 6 for x in range(len(namelist)): 7 for y in range(x+1,len(namelist)): 8 if namelist[x] == namelist[y]: 9 flag[y] = 1 10 break 11 for k in range(len(flag)-1,0,-1): 12 if flag[k] == 1: 13 del namelist[k] 14 print(flag) 15 print(namelist)
执行结果:
[0, 1, 0, 0, 0, 0, 1] ['Andy', 'Carol', 'Hanmeimei', 'Jack', 'Marry']