共計 749 個字符,預(yù)計需要花費(fèi) 2 分鐘才能閱讀完成。
Python 處理重復(fù)值的方法有以下幾種:
- 使用集合(set):將重復(fù)值放入一個集合中,集合會自動去除重復(fù)值。可以通過將列表轉(zhuǎn)化為集合再轉(zhuǎn)回列表的方式去除重復(fù)值。
lst = [1, 2, 3, 3, 4, 4, 5]
lst = list(set(lst))
print(lst) # 輸出 [1, 2, 3, 4, 5]
- 使用列表推導(dǎo)式:可以使用列表推導(dǎo)式來創(chuàng)建一個新列表,只保留原列表中的非重復(fù)值。
lst = [1, 2, 3, 3, 4, 4, 5]
lst = [x for i, x in enumerate(lst) if x not in lst[:i]]
print(lst) # 輸出 [1, 2, 3, 4, 5]
- 使用字典(dict)或計數(shù)器(Counter):可以將列表中的元素作為字典的鍵,出現(xiàn)的次數(shù)作為字典的值。然后可以根據(jù)字典的值來去除重復(fù)值。
from collections import Counter
lst = [1, 2, 3, 3, 4, 4, 5]
counter = Counter(lst)
lst = [x for x in counter if counter[x] == 1]
print(lst) # 輸出 [1, 2, 5]
- 使用 pandas 庫:pandas 庫提供了專門用于處理數(shù)據(jù)的數(shù)據(jù)結(jié)構(gòu)和函數(shù),可以用來處理重復(fù)值。可以使用 pandas 庫的
drop_duplicates()函數(shù)去除重復(fù)值。
import pandas as pd
lst = [1, 2, 3, 3, 4, 4, 5]
df = pd.DataFrame(lst, columns=['value'])
df = df.drop_duplicates()
lst = df['value'].tolist()
print(lst) # 輸出 [1, 2, 3, 4, 5]
以上是一些常見的方法,可以根據(jù)實(shí)際情況選擇合適的方法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完