- 方法一:使用set。此种方法会将列表内元素自动排序
In [1]: L = [3,2,4,6,5,6,1]
In [2]: L = set(L)
In [3]: list(L)
Out[3]: [1, 2, 3, 4, 5, 6]
- 方法二:使用字典函数,此种方法将不会改变列表内元素顺序
In [5]: L = [3,2,4,6,5,6,1]
In [6]: d = {}
In [7]: d = d.fromkeys(L)
In [8]: L = list(d.keys())
In [9]: L
Out[9]: [3, 2, 4, 6, 5, 1]
- 方法三:遍历列表,使用remove
In [10]: 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
...:
...:
In [11]: L = [3,2,4,6,5,6,1]
In [12]: L = delList(L)
In [13]: L
Out[13]: [3, 2, 4, 5, 6, 1]
- 方法四:遍历列表,使用append
In [15]: def delList(L):
...: L1 = []
...: for i in L:
...: if i not in L1:
...: L1.append(i)
...:
...: return L1
...:
...:
In [16]: L = delList(L)
In [17]: L
Out[17]: [3, 2, 4, 6, 5, 1]
- 方法五:使用filter,lambda,用于去除列表中所有某个特定的元素
In [18]: L = [3,2,4,6,5,6,1]
In [19]: f = filter(lambda n:n != 6, L)
In [20]: L = list(f)
In [21]: L
Out[21]: [3, 2, 4, 5, 1]
注:使用remove,只能去除第一个指定的元素。
最后随便介绍一下找出list重复元素的方法:
from collections import Counter
L = [3,2,4,6,5,6,1]
# 使用集合中的Counter
print({key: count for key, count in Counter(L).items() if count > 1})
# {6: 2}
# 或遍历列表
duplicate = {i: L.count(i) for i in L if L.count(i) > 1}
print(duplicate)
# {6: 2}