下面介绍了四种方法,删除一个列表中的重复元素
list1 = ['b', 'c', 'd', 'b', 'c', 'a', 'a']
# 去除list中的重复元素,且保持原来的顺序不变
def remove_repeat1(list1):
l2 = list(set(list1))
l2.sort(key=list1.index)
return l2
# 去除list中的重复元素,且保持原来的顺序不变
def remove_repeat2(list1):
l3 = []
for i in list1:
if i not in l3:
l3.append(i)
return l3
# 去除list中的重复元素,且保持原来的顺序不变
def remove_repeat3(list1):
from collections import OrderedDict
# d = OrderedDict.fromkeys(['a','b','c','a','b','c','c'])
d = OrderedDict.fromkeys(list1)
return list(d)
# 去除list中的重复元素,顺序会变
def remove_repeat4(list1):
return list(set(list1))
if __name__=='__main__':
list1 = ['b','c','d','b','c','a','a']
print remove_repeat1(list1) # 输出结果是:['b', 'c', 'd', 'a']
print remove_repeat2(list1) # 输出结果是:['b', 'c', 'd', 'a']
print remove_repeat3(list1) # 输出结果是:['b', 'c', 'd', 'a']
print remove_repeat1(list4) # 输出结果是:['a', 'c', 'b', 'd']