开发者社区> 问答> 正文

python list怎么去重复

python list怎么去重复

展开
收起
云计算小粉 2018-05-10 20:10:41 1904 0
3 条回答
写回答
取消 提交回答
  • 潜水砖家

    简单for循环

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

    set方式

    ids = [1,4,3,3,4,2,3,4,5,6,1]
    newIds = list(set(ids))
    newIds.sort(key=ids.index)  # 修正顺序

    reduce方式

    ids = [1,4,3,3,4,2,3,4,5,6,1]
    func = lambda x,y:x if y in x else x + [y]
    reduce(func, [[], ] + ids)
    2019-07-17 22:21:53
    赞同 展开评论 打赏
  • 这个人很懒,所以什么都不想留下~

    直接用set的话会导致之后的数据顺序发生改变,如果要还原顺序还要sort一下

    a = [3,1,4,7,4,3,1,6,7]
    b = list(set(a))
    b.sort(key=a.index)
    2019-07-17 22:21:52
    赞同 展开评论 打赏
  • 假设list为 tmp = [1,2,2,3] tmp = list(set(tmp))
    2019-07-17 22:21:52
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载