Python列表去重的幾種方法和實(shí)例
在 Python 中,列表去重有多種方法,下面分別介紹這些方法的實(shí)現(xiàn)。
方法一:使用 set() 函數(shù)
set() 函數(shù)可以將列表轉(zhuǎn)換成集合,集合中不允許有重復(fù)的元素,因此可以實(shí)現(xiàn)列表去重。
lst = [1, 2, 3, 3, 4, 4, 5]
lst = list(set(lst))
print(lst) # [1, 2, 3, 4, 5]
方法二:使用列表推導(dǎo)式
可以使用列表推導(dǎo)式,將列表中不重復(fù)的元素生成一個(gè)新的列表。
lst = [1, 2, 3, 3, 4, 4, 5]
lst = [i for i in lst if lst.count(i) == 1]
print(lst) # [1, 2, 5]
方法三:使用字典
通過(guò)字典的鍵唯一性,將列表中的元素作為鍵,生成一個(gè)字典,然后再將字典的鍵轉(zhuǎn)換成列表即可。
lst = [1, 2, 3, 3, 4, 4, 5]
d = {}
for i in lst:
d[i] = 1
lst = list(d.keys())
print(lst) # [1, 2, 3, 4, 5]
方法四:使用 Counter 對(duì)象
可以使用 Python 的 collections 模塊中的 Counter 對(duì)象,統(tǒng)計(jì)列表中每個(gè)元素的出現(xiàn)次數(shù),然后再將出現(xiàn)次數(shù)為 1 的元素生成一個(gè)新的列表。
from collections import Counter
lst = [1, 2, 3, 3, 4, 4, 5]
c = Counter(lst)
lst = [k for k, v in c.items() if v == 1]
print(lst) # [1, 2, 5]
方法五:使用 Pandas 庫(kù)
可以使用 Pandas 庫(kù)中的 drop_duplicates() 函數(shù),將列表轉(zhuǎn)換成 Pandas 的數(shù)據(jù)框,然后再使用該函數(shù)去重。
import pandas as pd
lst = [1, 2, 3, 3, 4, 4, 5]
df = pd.DataFrame(lst)
lst = list(df.drop_duplicates()[0])
print(lst) # [1, 2, 3, 4, 5]
方法六:使用 Numpy 庫(kù)
可以使用 Numpy 庫(kù)中的 unique() 函數(shù),將列表轉(zhuǎn)換成 Numpy 數(shù)組,然后再使用該函數(shù)去重。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-458128.html
import numpy as np
lst = [1, 2, 3, 3, 4, 4, 5]
lst = np.array(lst)
lst = list(np.unique(lst))
print(lst) # [1, 2, 3, 4, 5]
這些方法都可以實(shí)現(xiàn)列表去重,具體選擇哪個(gè)方法,可以根據(jù)實(shí)際情況選擇。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-458128.html
到了這里,關(guān)于Python列表去重的幾種方法和實(shí)例的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!