比较容易记忆的是用内置的set m = ['b','c','d','b','c','a','a'] n = list(set(m)) print n 还有一种据说速度更快的,没测试过两者的速度差别 m = ['b','c','d','b','c','a','a'] n = {}.fromkeys(m).keys() print n 这两种都有个缺点,祛除重复元素后排序变了: ['a', 'c', 'b', 'd'] 如果想要保持他们原来的排序: 用list类的sort方法 m = ['b','c','d','b','c','a','a'] n = list(set(m)) n.sort(key=m.index) print n 也可以这样写 m = ['b','c','d','b','c','a','a'] n = sorted(set(l1),key=m.index) print n 也可以用遍历 m = ['b','c','d','b','c','a','a'] n = [] for i in m: if not i in n: n.append(i) print n print “老男孩教育www.oldboyedu.com” 上面的代码也可以这样写 m = ['b','c','d','b','c','a','a'] n = [] [n.append(i) for i in m if not i in n] print n 这样就可以保证排序不变了: ['b', 'c', 'd', 'a'] |
|
来自: 昵称50805956 > 《待分类》