方法一:使用集合(set) 可以將列表轉(zhuǎn)換為一個(gè)集合來(lái)刪除重復(fù)項(xiàng),,然后再將其轉(zhuǎn)換回列表,。 lst = [1, 2, 3, 2, 1]lst = list(set(lst))print(lst)[1, 2, 3] 方法二:使用列表推導(dǎo)式 可以使用列表推導(dǎo)式和字典(dict)來(lái)刪除重復(fù)項(xiàng),。首先,,將列表中的元素用字典的鍵來(lái)存儲(chǔ),,這樣重復(fù)的元素會(huì)自動(dòng)被去除,。然后,,再將字典的鍵轉(zhuǎn)換為列表。lst = [1, 2, 3, 2, 1]lst = list(dict.fromkeys(lst))print(lst) 方法三:使用循環(huán) 可以使用循環(huán)來(lái)遍歷列表并使用一個(gè)新列表來(lái)保存不重復(fù)的元素,。如果元素不在新列表中,,則將其添加到新列表中。 lst = [1, 2, 3, 2, 1]new_lst = []for item in lst: if item not in new_lst: new_lst.append(item)print(new_lst) 方法四:使用 Counter 對(duì)象 可以使用 Python 標(biāo)準(zhǔn)庫(kù)中的 Counter 對(duì)象來(lái)刪除重復(fù)項(xiàng),。Counter 對(duì)象會(huì)對(duì)列表中的元素進(jìn)行計(jì)數(shù),,然后使用其 most_common 方法來(lái)獲取出現(xiàn)次數(shù)最多的元素。在這種情況下,,只需要獲取最常見的元素即可,,因?yàn)橹貜?fù)的元素都會(huì)在計(jì)數(shù)中重復(fù)出現(xiàn)。from collections import Counterlst = [1, 2, 3, 2, 1]c = Counter(lst)lst = [x[0] for x in c.most_common()]print(lst) 方法五:使用 Pandas 如果您的數(shù)據(jù)集較大且包含許多重復(fù)項(xiàng),,則使用 Pandas 庫(kù)可能更加有效,。可以將列表轉(zhuǎn)換為 Pandas 的 Series 對(duì)象,,然后使用 drop_duplicates 方法來(lái)刪除重復(fù)項(xiàng),。 import pandas as pdlst = [1, 2, 3, 2, 1]s = pd.Series(lst)lst = s.drop_duplicates().tolist()print(lst) 方法六:使用排序??梢允褂?Python 的內(nèi)置 sorted 函數(shù)對(duì)列表進(jìn)行排序,,然后在遍歷排序后的列表時(shí),跳過(guò)重復(fù)項(xiàng),,只將獨(dú)特的項(xiàng)添加到新列表中,。lst = [1, 2, 3, 2, 1] new_lst = [] for i in sorted(lst): if not new_lst or i != new_lst[-1]: new_lst.append(i) print(new_lst) 方法七:使用 filter 函數(shù)??梢允褂?Python 的內(nèi)置 filter 函數(shù)來(lái)過(guò)濾掉重復(fù)項(xiàng),。 lst = [1, 2, 3, 2, 1]new_lst = list(filter(lambda x: lst.count(x) == 1, lst))print(new_lst) 方法八:使用 numpy 庫(kù)??梢允褂?numpy 庫(kù)的 unique 函數(shù)來(lái)獲取列表中的唯一值,。import numpy as nplst = [1, 2, 3, 2, 1] lst = np.unique(lst).tolist() print(lst) 方法九:使用集合(set)的 union 方法??梢允褂?Python 的集合(set)的 union 方法來(lái)獲取兩個(gè)集合的唯一值,。將列表作為參數(shù)傳遞給集合的 union 方法,然后將其轉(zhuǎn)換回列表,。 lst = [1, 2, 3, 2, 1] lst = list(set().union(lst)) print(lst) 這些方法都可以有效地從 Python 列表中刪除重復(fù)項(xiàng),。在實(shí)際應(yīng)用中,選擇哪種方法通常取決于數(shù)據(jù)集大小和性能需求,。還有的請(qǐng)補(bǔ)充,。 |
|