首页 > 编程知识 正文

列表去重 python,python对列表进行去重

时间:2023-05-06 04:00:04 阅读:274876 作者:84

这篇文章主要为大家详细介绍了Python列表去重的4种实现方法,具有一定的参考价值,可以用来参考一下。

对python这个高级语言感兴趣的小伙伴,下面一起跟随512笔记的小编两巴掌来看看吧!

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

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

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

# @param Python对列表去重的4种方法

# @author 512笔记|512Pic.com

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

#list()方法是把字符串str或元组转成数组

formatList = list(set(orgList))

print (formatList)

# End www_512pic_com

结果:

[0, 1, 3, 5, 7]

# End www_512pic_com

2. 使用keys()方法

# @param Python对列表去重的4种方法

# @author 512笔记|512Pic.com

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

#list()方法是把字符串str或元组转成数组

formatList = list({}.fromkeys(orgList).keys())

print (formatList)

# End www_512pic_com

结果:

[0, 1, 3, 5, 7]

# End www_512pic_com

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

3. 循环遍历法

# @param Python对列表去重的4种方法

# @author 512笔记|512Pic.com

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

formatList = []

for id in orgList:

if id not in formatList:

formatList.append(id)

print (formatList)

# End www_512pic_com

结果:

[1, 0, 3, 7, 5]

# End www_512pic_com

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

4. 按照索引再次排序

# @param Python对列表去重的4种方法

# @author 512笔记|512Pic.com

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

formatList = list(set(orgList))

formatList.sort(key=orgList.index)

print (formatList)

# End www_512pic_com

结果:

[1, 0, 3, 7, 5]

# End www_512pic_com

注:关于Python列表去重的4种实现方法的内容就先介绍到这里,更多相关文章的可以留意512笔记的其他信息。

关键词:去重

您可能感兴趣的文章

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。