栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python对列表去重的4种方法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python对列表去重的4种方法

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

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

1. 使用set的特型,python的set和其他语言类似, 是一个无序不重复元素集
orgList = [1,0,3,7,7,5]
#list()方法是把字符串str或元组转成数组
formatList = list(set(orgList))
print (formatList)

结果:

[0, 1, 3, 5, 7]


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

结果:

[0, 1, 3, 5, 7]


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


3. 循环遍历法
orgList = [1,0,3,7,7,5]
formatList = []
for id in orgList:
    if id not in formatList:
        formatList.append(id)
print (formatList)

结果:

[1, 0, 3, 7, 5]

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


4. 按照索引再次排序
orgList = [1,0,3,7,7,5]
formatList = list(set(orgList))
formatList.sort(key=orgList.index)
print (formatList)

结果:

[1, 0, 3, 7, 5]

原文来源:https://m.pythontab.com/article/1194


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/219929.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号