• 技术文章 >Python技术 >Python基础教程

    Python list如何去重

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-09-21 16:11:39原创8369

    直观方法

    最简单的思路就是:

    ids = [1,2,3,3,4,2,3,4,5,6,1]
    news_ids = []
    for id in ids:
        if id not in news_ids:
            news_ids.append(id)
    
    print news_ids

    相关推荐:《Python基础教程

    使用set方法

    ids = [1,4,3,3,4,2,3,4,5,6,1]
    ids = list(set(ids))

    这样的结果是没有保持原来的顺序。

    按照索引再次排序

    最后通过这种方式解决:

    ids = [1,4,3,3,4,2,3,4,5,6,1]
    news_ids = list(set(ids))
    news_ids.sort(key=ids.index)

    使用itertools.grouby方法

    如果不考虑列表顺序的话可用这个:

    ids = [1,4,3,3,4,2,3,4,5,6,1]
    ids.sort()
    it = itertools.groupby(ids)
     
    for k, g in it:
        print k

    关于itertools.groupby的原理可以看这里:http://docs.python.org/2/library/itertools.html#itertools.groupby

    使用reduce方法

    In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]
    In [6]: func = lambda x,y:x if y in x else x + [y]
    In [7]: reduce(func, [[], ] + ids)
    Out[7]: [1, 4, 3, 2, 5, 6]

    上面是我在ipython中运行的代码,其中的 lambda x,y:x if y in x else x + [y] 等价于 lambda x,y: y in x and x orx+[y] 。

    思路其实就是先把ids变为[[], 1,4,3,......],然后在利用reduce的特性。

    reduce解释参看这里:http://docs.python.org/2/library/functions.html#reduce

    专题推荐:list 去重 python
    品易云
    上一篇:python中simhash包怎么用 下一篇:python如何输入参数个数

    相关文章推荐

    • python的list如何去重• python如何删除list• python如何对list求和• python如何输出list

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网