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

yipeiwu_com7年前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使用迭代器捕获Generator返回值的方法

本文实例讲述了Python使用迭代器捕获Generator返回值的方法。分享给大家供大家参考,具体如下: 用for循环调用generator时,发现拿不到generator的return...

使用IDLE的Python shell窗口实例详解

使用IDLE的Python shell窗口实例详解

启动IDLE后会打开Python shell窗口。当键入代码 时,它会基于Python语法提供自动缩进和代码着色功能。 使用IDLE中的Python shell。代码在输入时会自动着...

python快速排序代码实例

一、 算法描述: 1.先从数列中取出一个数作为基准数。2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。3.再对左右区间重复第二步,直到各区间只有一个数。 &...

Python中对数组集进行按行打乱shuffle的方法

如下所示: import numpy as np y1=np.random.randint(2,10,(5,3)) print ("排序列表:", y1) np.random.shu...

tornado+celery的简单使用详解

celery是实现一个简单,灵活可靠的分布式任务队列系统的好选择 tornado则不用过多介绍 在开发机上安装rabbitmq这里就不介绍了 首先是task文件的编写 task.py...