新聞中心

成都創(chuàng)新互聯(lián)是少有的成都做網(wǎng)站、成都網(wǎng)站建設、營銷型企業(yè)網(wǎng)站、微信小程序開發(fā)、手機APP,開發(fā)、制作、設計、外鏈、推廣優(yōu)化一站式服務網(wǎng)絡公司,于2013年成立,堅持透明化,價格低,無套路經(jīng)營理念。讓網(wǎng)頁驚喜每一位訪客多年來深受用戶好評
直觀方法
最簡單的思路就是:
ids = [1,2,3,3,4,2,3,4,5,6,1] news_ids = [] for id in ids: if id not in news_ids: news_ids.append(id) print news_ids
相關推薦:《python基礎教程》
使用set方法
ids = [1,4,3,3,4,2,3,4,5,6,1] ids = list(set(ids))
這樣的結果是沒有保持原來的順序。
按照索引再次排序
最后通過這種方式解決:
ids = [1,4,3,3,4,2,3,4,5,6,1] news_ids = list(set(ids)) news_ids.sort(key=ids.index)
使用itertools.grouby方法
如果不考慮列表順序的話可用這個:
ids = [1,4,3,3,4,2,3,4,5,6,1] ids.sort() it = itertools.groupby(ids) for k, g in it: print k
關于itertools.groupby的原理可以看這里:http://docs.python.org/2/library/itertools.html#itertools.groupby
使用reduce方法
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1] In [6]: func = lambda x,y:x if y in x else x + [y] In [7]: reduce(func, [[], ] + ids) Out[7]: [1, 4, 3, 2, 5, 6]
上面是我在ipython中運行的代碼,其中的 lambda x,y:x if y in x else x + [y] 等價于 lambda x,y: y in x and x orx+[y] 。
思路其實就是先把ids變?yōu)閇[], 1,4,3,......],然后在利用reduce的特性。
reduce解釋參看這里:http://docs.python.org/2/library/functions.html#reduce
當前名稱:創(chuàng)新互聯(lián)Python教程:Pythonlist如何去重
URL網(wǎng)址:http://www.5511xx.com/article/cdeshoe.html


咨詢
建站咨詢
