Python实现嵌套列表去重方法示例

yipeiwu_com6年前Python基础

发现问题

python嵌套列表大家应该都不陌生,但最近遇到了一个问题,这是工作中遇到的一个坑,首先看一下问题

raw_list = [["百度", "CPY"], ["京东", "CPY"], ["黄轩", "PN"], ["百度", "CPY"]]

列表嵌套了列表,并且有一个重复列表["百度", "CPY"],现在要求将这个重复元素进行去重(重复是指嵌套的列表内两个元素都相同),并且保证元素顺序不变,输出还是嵌套列表,即最后结果应该长这样:[["百度", "CPY"], ["京东", "CPY"], ["黄轩", "PN"]]

正常Python去重都是使用set,所以我这边也是用这种思想处理一下

In [8]: new_list = [list(t) for t in set(tuple(_) for _ in raw_list)]
In [9]: new_list
Out[9]: [['京东', 'CPY'], ['百度', 'CPY'], ['黄轩', 'PN']]

=。=以为大功告成,结果发现嵌套列表顺序变了

好吧一步步找一下是从哪边顺序变了的

In [10]: s = set(tuple(_) for _ in raw_list)
In [11]: s
Out[11]: {('京东', 'CPY'), ('百度', 'CPY'), ('黄轩', 'PN')}

恍然大悟关于set的两个关键词:无序 和 不重复 =。=

所以从set解决排序问题基本无望了,然而我还没有放弃,现在问题就变成了对于new_list怎么按照raw_list元素顺序排序,当然肯定要通过sort实现

翻一下Python文档找到以下一段话

文档地址

sort(*, key=None, reverse=False)

This method sorts the list in place, using only < comparisons between 
items. Exceptions are not suppressed - if any comparison operations  
fail, the entire sort operation will fail (and the list will likely be left in a 
 partially modified state).

 [`sort()`](https://docs.python.org/3/library/stdtypes.html?highlight=sort#list.sort "list.sort") 

accepts two arguments that can only be passed by keyword ( [keyword-only arguments](https://docs.python.org/3/glossary.html#keyword-only-parameter) ):

key specifies a function of one argument that is used to extract a 
comparison key from each list element (for example, key=str.lower). 
 The key corresponding to each item in the list is calculated once and  then used for the entire sorting process. The default value of None 
means that list items are sorted directly without calculating a separate
 key value.

开始划重点:

sort方法通过参数key指定一个方法,换句话说,key参数的值是函数。

这个函数和new_list上的每个元素会产生一个结果,sort通过这个结果进行排序。

于是这里就想到求出new_list里的每一个元素在raw_list里的索引,根据这个索引进行排序。

代码实现如下:

In [13]: new_list.sort(key=raw_list.index)
In [14]: new_list
Out[14]: [['百度', 'CPY'], ['京东', 'CPY'], ['黄轩', 'PN']]

结果和期望一样 =。=

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python脚本按照当前日期创建多级目录

使用python脚本按照年月日生成多级目录,创建的目录可以将系统生成的日志文件放入其中,方便查阅,代码如下: #!/usr/bin/env python #coding=utf-8...

Centos5.x下升级python到python2.7版本教程

首先到官网下载python2.7.3版本,编译安装 复制代码 代码如下: $wget http://www.python.org/ftp/python/2.7.3/Python-2.7....

Python中正则表达式的用法总结

正则表达式很神奇啊 # -*- coding:utf-8 -*- import re def print_match_res(res): """打印匹配对象内容""" if...

python批量读取txt文件为DataFrame的方法

python批量读取txt文件为DataFrame的方法

我们有时候会批量处理同一个文件夹下的文件,并且希望读取到一个文件里面便于我们计算操作。比方我有下图一系列的txt文件,我该如何把它们写入一个txt文件中并且读取为DataFrame格式呢...

python中的split()函数和os.path.split()函数使用详解

Python中有split()和os.path.split()两个函数: split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。 os.path.spli...