无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

(python list 去重) Python对列表去重的多种方法(四种方法) Python 列表去重四种方法 全网首发(图文详解1)

前沿技术 Micheal 4个月前 (05-28) 44次浏览 已收录 扫描二维码

(python list 去重) Python对列表去重的多种方法(四种方法)

好的,关于Python对列表去重,这里给你介绍四种方法,并展示了具体的代码。

方法一:使用set()函数

def remove_duplicates(input_list):
    return list(set(input_list))

duplicates_list = [1, 2, 2, 3, 4, 5, 5, 6, 6]
print(remove_duplicates(duplicates_list))  
# 输出结果 [1, 2, 3, 4, 5, 6]

上述代码中,我们首先使用set函数去重,然后再将得到的set对象转化回list。这个方法简单高效,但不会保持原列表中的元素顺序。

方法二:使用列表推导式

def remove_duplicates(input_list):
    return [input_list[i] for i in range(len(input_list)) if input_list[i] not in input_list[:i]]

duplicates_list = [1, 2, 2, 3, 4, 5, 5, 6, 6]
print(remove_duplicates(duplicates_list))  
# 输出结果 [1, 2, 3, 4, 5, 6]

这个方法会遍历输入的列表,只有当元素不在已经遍历过的部分列表中,才将其添加入结果列表,这种方法可以保持原列表的顺序。

方法三:使用字典的fromkeys()函数

def remove_duplicates(input_list):
    return list(dict.fromkeys(input_list))

duplicates_list = [1, 2, 2, 3, 4, 5, 5, 6, 6]
print(remove_duplicates(duplicates_list))  
# 输出结果 [1, 2, 3, 4, 5, 6]

fromkeys()函数会为字典生成一组新的键,然后我们再将字典转为列表。这种方法也能保持元素的顺序。

方法四:使用库函数
例如使用pandas库的drop_duplicates()函数

import pandas as pd

def remove_duplicates(input_list):
    df = pd.DataFrame(input_list, columns=['values'])
    df = df.drop_duplicates()
    return df['values'].tolist()

duplicates_list = [1, 2, 2, 3, 4, 5, 5, 6, 6]
print(remove_duplicates(duplicates_list))  
# 输出结果 [1, 2, 3, 4, 5, 6]

这种方法需要安装pandas库,并且适用性较广,可处理复杂情况例如数据框的去重等。

以上介绍了四种Python去重的方法,你可以根据需求选择适合的方法。
(421) http请求报错:421 Misdirected Request的原因和解决办法 HTTP错误421:Misdirected Request原因和解决方法 全网首发(图文详解1)
(417) http请求报错:417 Expectation Failed的原因和解决办法 HTTP 417 Expectation Failed解决方案 全网首发(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝