python中列表实现去重使用_Python实现嵌套列表去重方法示例
發(fā)現(xiàn)問(wèn)題
python嵌套列表大家應(yīng)該都不陌生,但最近遇到了一個(gè)問(wèn)題,這是工作中遇到的一個(gè)坑,首先看一下問(wèn)題
raw_list = [["百度", "CPY"], ["京東", "CPY"], ["黃軒", "PN"], ["百度", "CPY"]]
列表嵌套了列表,并且有一個(gè)重復(fù)列表["百度", "CPY"],現(xiàn)在要求將這個(gè)重復(fù)元素進(jìn)行去重(重復(fù)是指嵌套的列表內(nèi)兩個(gè)元素都相同),并且保證元素順序不變,輸出還是嵌套列表,即最后結(jié)果應(yīng)該長(zhǎng)這樣:[["百度", "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']]
=。=以為大功告成,結(jié)果發(fā)現(xiàn)嵌套列表順序變了
好吧一步步找一下是從哪邊順序變了的
In [10]: s = set(tuple(_) for _ in raw_list)
In [11]: s
Out[11]: {('京東', 'CPY'), ('百度', 'CPY'), ('黃軒', 'PN')}
恍然大悟關(guān)于set的兩個(gè)關(guān)鍵詞:無(wú)序 和 不重復(fù) =。=
所以從set解決排序問(wèn)題基本無(wú)望了,然而我還沒(méi)有放棄,現(xiàn)在問(wèn)題就變成了對(duì)于new_list怎么按照raw_list元素順序排序,當(dāng)然肯定要通過(guò)sort實(shí)現(xiàn)
翻一下Python文檔找到以下一段話(huà)
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.
開(kāi)始劃重點(diǎn):
sort方法通過(guò)參數(shù)key指定一個(gè)方法,換句話(huà)說(shuō),key參數(shù)的值是函數(shù)。
這個(gè)函數(shù)和new_list上的每個(gè)元素會(huì)產(chǎn)生一個(gè)結(jié)果,sort通過(guò)這個(gè)結(jié)果進(jìn)行排序。
于是這里就想到求出new_list里的每一個(gè)元素在raw_list里的索引,根據(jù)這個(gè)索引進(jìn)行排序。
代碼實(shí)現(xiàn)如下:
In [13]: new_list.sort(key=raw_list.index)
In [14]: new_list
Out[14]: [['百度', 'CPY'], ['京東', 'CPY'], ['黃軒', 'PN']]
結(jié)果和期望一樣 =。=
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)我們的支持。
時(shí)間: 2017-12-25
總結(jié)
以上是生活随笔為你收集整理的python中列表实现去重使用_Python实现嵌套列表去重方法示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 页面置换算法及例题
- 下一篇: python全栈开发优势_Python全