python的列表(数组)无比强大,下面介绍集中去除列表中重复元素的方法,各有利弊,可根据需要选用
最简单的方法是使用集合set,这种方法会改变列表的原有顺序
l1 = ['b','c','d','b','c','a','a'] l2 = list(set(l1)) print l2
输出结果:
[‘a’, ‘c’, ‘b’, ‘d’]
还有一种据说速度更快的,没测试过两者的速度差别
l1 = ['b','c','d','b','c','a','a'] l2 = {}.fromkeys(l1).keys() print l2
输出结果:
[‘a’, ‘c’, ‘b’, ‘d’]
这两种都有个缺点,去除重复元素后排序变了:
[‘a’, ‘c’, ‘b’, ‘d’]
如果想要保持他们原来的排序:
用list类的sort方法
l1 = ['b','c','d','b','c','a','a'] l2 = list(set(l1)) l2.sort(key=l1.index) print l2
输出结果:
[‘b’, ‘c’, ‘d’, ‘a’]
也可以这样写
l1 = ['b','c','d','b','c','a','a'] l2 = sorted(set(l1),key=l1.index) print l2
输出结果:
[‘b’, ‘c’, ‘d’, ‘a’]
也可以用遍历
l1 = ['b','c','d','b','c','a','a'] l2 = [] for i in l1: if not i in l2: l2.append(i) print l2
上面的代码也可以这样写
l1 = ['b','c','d','b','c','a','a'] l2 = [] [l2.append(i) for i in l1 if not i in l2] print l2
输出结果:
[‘b’, ‘c’, ‘d’, ‘a’]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/8182.html