郑州网站建设汉狮,微信seo排名优化软件,如何在网上销售,0元建设黑网站发现问题python嵌套列表大家应该都不陌生#xff0c;但最近遇到了一个问题#xff0c;这是工作中遇到的一个坑#xff0c;首先看一下问题raw_list [[百度, CPY], [京东, CPY], [黄轩, PN], [但最近遇到了一个问题这是工作中遇到的一个坑首先看一下问题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_listOut[9]: [[京东, CPY], [百度, CPY], [黄轩, PN]]。以为大功告成结果发现嵌套列表顺序变了好吧一步步找一下是从哪边顺序变了的In [10]: s set(tuple(_) for _ in raw_list)In [11]: sOut[11]: {(京东, CPY), (百度, CPY), (黄轩, PN)}恍然大悟关于set的两个关键词无序 和 不重复 。所以从set解决排序问题基本无望了然而我还没有放弃现在问题就变成了对于new_list怎么按照raw_list元素顺序排序当然肯定要通过sort实现翻一下Python文档找到以下一段话sort(*, keyNone, reverseFalse)This method sorts the list in place, using only comparisons betweenitems. Exceptions are not suppressed - if any comparison operationsfail, the entire sort operation will fail (and the list will likely be left in apartially modified state).[sort()](https://docs.python.org/3/library/stdtypes.html?highlightsort#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 acomparison key from each list element (for example, keystr.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 Nonemeans that list items are sorted directly without calculating a separatekey value.开始划重点sort方法通过参数key指定一个方法换句话说key参数的值是函数。这个函数和new_list上的每个元素会产生一个结果sort通过这个结果进行排序。于是这里就想到求出new_list里的每一个元素在raw_list里的索引根据这个索引进行排序。代码实现如下In [13]: new_list.sort(keyraw_list.index)In [14]: new_listOut[14]: [[百度, CPY], [京东, CPY], [黄轩, PN]]结果和期望一样 。总结以上就是这篇文章的全部内容了希望本文的内容对大家的学习或者工作具有一定的参考学习价值如果有疑问大家可以留言交流谢谢大家对的支持。