發現問題
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']]
結果和期望一樣 =。=
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對我們的支持。
時間: 2017-12-25