python中刪除列表中屢次重複的元素

一、ide

>>> test1 = ["aa","bb","aa","cc","aa","cc","dd","ee"]
>>> test1
['aa', 'bb', 'aa', 'cc', 'aa', 'cc', 'dd', 'ee']
>>> "aa" in test1
True
>>> test1.count("aa")
3
>>> while "aa" in test1:
    test1.remove("aa")
    print(1)

    
1
1
1
>>> test1
['bb', 'cc', 'cc', 'dd', 'ee']

 

二、rem

>>> test1 = ["aa","bb","aa","cc","aa","cc","dd","ee"]
>>> test2 = list(set(test1))
>>> test2
['bb', 'dd', 'ee', 'aa', 'cc']
>>> for i in test2:
    if test1.count(i) == 1:
        test2.remove(i)

        
>>> test2
['dd', 'aa', 'cc']    ## ???????? 



>>> test2 = list(set(test1)) >>> test3 = test2.copy() >>> test2 == test3 True >>> test2 ['bb', 'dd', 'ee', 'aa', 'cc'] >>> test3 ['bb', 'dd', 'ee', 'aa', 'cc'] >>> for i in test2: if test1.count(i) == 1: test3.remove(i) >>> test3 ['aa', 'cc']

 

>>> test3
['aa', 'cc']
>>> test1
['aa', 'bb', 'aa', 'cc', 'aa', 'cc', 'dd', 'ee']
>>> test3
['aa', 'cc']
>>> for i in test3:
    while i in test1:
        test1.remove(i)

        
>>> test1
['bb', 'dd', 'ee']
相關文章
相關標籤/搜索