zoukankan      html  css  js  c++  java
  • Python list去重

    http://www.cnblogs.com/feisky/archive/2012/12/06/2805251.html

    比较容易记忆的是用内置的set
    l1 = ['b','c','d','b','c','a','a']
    l2 = list(set(l1))
    print l2
    还有一种据说速度更快的,没测试过两者的速度差别
    l1 = ['b','c','d','b','c','a','a']
    l2 = {}.fromkeys(l1).keys()
    print l2
    这两种都有个缺点,祛除重复元素后排序变了:
    ['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
    也可以这样写
    l1 = ['b','c','d','b','c','a','a']
    l2 = sorted(set(l1),key=l1.index)
    print l2
    也可以用遍历
    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']

  • 相关阅读:
    自我介绍
    币值转换
    打印沙漏
    对我影响最大的三位老师

    pta
    pta-3
    学习计划
    对我有影响的三个老师
    介绍自己
  • 原文地址:https://www.cnblogs.com/adodo1/p/4328172.html
Copyright © 2011-2022 走看看