python 列表去重(數組)的幾種方法

    python 列表就是我們js中的數組了,我們下文整理幾個常用的python 列表去重實現方法,非常的簡單好用。
     在抓取頁面圖片時,爲避免重複抓取,將抓取的img結果(結果集是list類型的)通過集合去重。這裏總結了下網上蒐集到的幾種方法。

一、方法1

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

二、方法2思路看起來比較清晰簡單 ,也可以保持之前的排列順序。

通過set方法進行處理

ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))

處理起來比較簡單,使用了集合方法set進行處理,不過結果不會保留之前的順序。

三、方法3

利用lambda匿名函數和 reduce 函數處理

ids = [1,4,3,3,4,2,3,4,5,6,1]
func = lambda x,y:x if y in x else x + [y]
reduce(func, [[], ] + ids)

四、方法4

使用itertools模塊

import itertools
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

五、無法保持原有順序

liebiao=set(liebiao)

六、while遍歷去重

def delRepeat(liebiao):
 for x in liebiao:
  while liebiao.count(x)>1:
   del liebiao[liebiao.index(x)]
 return liebiao

七、例子

程序很簡單,直接上代碼吧:

#coding=utf-8
          
def open_txt():  #打開TXT文本寫入數組
    try:
        xxx = file(r'C:\Users\Administrator\Desktop\user.txt', 'r')
        for xxx_line in xxx.readlines():
            passlist.append(xxx_line)
        xxx.close()
    except:
        return 0
          
def write_txt():  #打開TXT文本寫入數組
    try:
        yyy = file(r'C:\Users\Administrator\Desktop\list_user.txt', 'w')
        for i in list_passwed:
            yyy.write(i)
        yyy.close()
    except:
        return 0
          
          
global  passlist  #聲明全局變量
passlist = []    #用戶名:anonymous 密碼爲空
open_txt()   #TXT導入數組
#passlist = list(set(passlist))   #python 列表去重
global  list_passwed  #列表去重,不打亂原來的順序
list_passwed=[]
for i in passlist:
    if i not in list_passwed:
        list_passwed.append(i)
write_txt()<span style="font-family: Simsun; background-color: rgb(255, 255, 255);"> </span>

aside# set方法可以直接去重而且還會排序,如果需要排序的話用set是最快的

轉載:python 列表去重(數組)的幾種方法


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章