直接上代码:
# encoding=utf8
import itertools
def dup_remove(lis, i):
if i in lis:
return lis
else:
return lis + [i]
def main():
l = ['b','c','d','b','c','a','a']
# 利用set
print list(set(l))
# 利用字典
print {}.fromkeys(l, 1).keys()
# 列表推导式
m = []
[m.append(i) for i in l if i not in m]
print m
# 利用reduce:http://www.runoob.com/python/python-func-reduce.html
func = lambda x, y: x if y in x else x + [y]
m = reduce(func, [[], ] + l)
print m
# 将上面的lambda函数换成普通函数
m = reduce(dup_remove, [[], ] + l)
print m
# 使用itertools.groupby:http://www.cnblogs.com/vamei/p/3174796.html
m = []
l.sort() # 分组之前需要使用sorted()对原循环器的元素,根据key函数进行排序,让同组元素先在位置上靠拢。
it = itertools.groupby(l)
for k, v in it:
m.append(k)
print m
if __name__ == '__main__':
main()
运行结果:
['a', 'c', 'b', 'd']
['a', 'c', 'b', 'd']
['b', 'c', 'd', 'a']
['b', 'c', 'd', 'a']
['b', 'c', 'd', 'a']
['a', 'b', 'c', 'd']