簡體   English   中英

刪除列表中的重復項並檢查它是否與另一個列表相同

[英]Remove duplicates in a list and check whether it's the same as another list

我的任務是實現'remove_extra(lst)',這樣它就會獲取一個列表並返回相同的列表,並刪除所有重復的出現。 注意:返回列表中元素的順序無關緊要。 提示:您可以使用sort或任何其他python列表函數來使您的生活更輕松。

我得到了:

lst1 = [1, 5, 1, 1, 3]
lst2 = [2, 2, 2, 1, 5, 4, 4]
result1 = remove_extra(lst1)
result2 = remove_extra(lst2)

執行以下表達式時:

(result1 is lst1)
(result2 is lst2)

我應該為兩個表達式都得到True但我的輸出是False。 請幫我查一下我的代碼:

def remove_extra(lst):
    new_lst = []
    for i in lst:
        if i not in new_lst:
        new_lst.append(i)

    return new_lst

如果需要就地更改lst ,請指定整個切片; 使用set()生成一系列唯一值而不是循環:

def remove_extra(lst):
    lst[:] = set(lst)
    return lst

分配給切片會替換列表中的元素 ,而不是重新綁定名稱lst 對於標識切片(從第一個元素到最后一個元素),這意味着我們用賦值右側的序列中包含的任何元素替換所有元素。 lst[:] = set(lst)替換所有元素lst與該中的同一列表的元素。

但是,最好不要為就地操作返回相同的列表對象。 沒有什么意義,原來的名單已經改變了; 當可變對象被直接更改時,Python內置類型總是返回None

演示:

>>> lst1 = [1, 5, 1, 1, 3]
>>> def remove_extra(lst):
...     lst[:] = set(lst)
...     return lst
... 
>>> lst1 = [1, 5, 1, 1, 3]
>>> result1 = remove_extra(lst1)
>>> result1 is lst1
True
>>> lst1
[1, 3, 5]
>>> lst2 = [2, 2, 2, 1, 5, 4, 4]
>>> result2 = remove_extra(lst2)
>>> result2 is lst2
True

我通常會使用list(set(...))實現,但只是為了好玩,這里有一個不同的方式:

L = [2, 2, 2, 1, 5, 4, 4]
L.sort()
i = 0
while i<len(L)-1:
    print("j:", j)
    while L[i]==L[j] and j<len(L):
        L.pop(j)
    i += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM