zoukankan      html  css  js  c++  java
  • pyhon列表去重方法总结

    开发中对数组、列表去重是非常常见的需求,对一个list中的id进行去重,有下面几种方法,前面两种方法不能保证顺序, 后面两种方法可以保持原来的顺序。

    下面的代码都在Python3下测试通过, Python2下请自行测试

    1. 使用set的特型,python的set和其他语言类似, 是一个无序不重复元素集

    1
    2
    3
    4
    orgList = [1,0,3,7,7,5]
    #list()方法是把字符串str或元组转成数组
    formatList = list(set(orgList))
    print (formatList)

    结果:

    1
    [0, 1, 3, 5, 7]

    2. 使用keys()方法

    1
    2
    3
    4
    orgList = [1,0,3,7,7,5]
    #list()方法是把字符串str或元组转成数组
    formatList = list({}.fromkeys(orgList).keys())
    print (formatList)

    结果:

    1
    [0, 1, 3, 5, 7]

    上面两种方法的问题是:结果是没有保持原来的顺序。

    3. 循环遍历法

    1
    2
    3
    4
    5
    6
    orgList = [1,0,3,7,7,5]
    formatList = []
    for id in orgList:
        if id not in formatList:
            formatList.append(id)
    print (formatList)

    结果:

    1
    [1, 0, 3, 7, 5]

    but,这样的代码不够简洁,不够高端

    4. 按照索引再次排序

    1
    2
    3
    4
    orgList = [1,0,3,7,7,5]
    formatList = list(set(orgList))
    formatList.sort(key=orgList.index)
    print (formatList)

    结果:

    1
    [1, 0, 3, 7, 5]
  • 相关阅读:
    Linux 02
    Linux 01
    React 函数式组件的 Ref 和子组件访问(useImperativeHandle)
    排序算法之 Java插入排序算法
    排序算法之 Java选择排序算法
    排序算法之 Java冒泡算法
    类加载的过程---验证和准备
    类加载的过程---加载
    mysql explain 查询处理的结果详解
    springboot整合分布式缓存hazelCast
  • 原文地址:https://www.cnblogs.com/Kingfan1993/p/9570089.html
Copyright © 2011-2022 走看看