干货不看看嘛:python列表去重的5种方法

方法收集自python群大佬

数据用例

lst1 = [1,2,2,3,4,3,5,2]
lst2 = [1,6,5,6,4,3,2,1]

1、精简逻辑版

利用 not in 快速筛查,非常Pythonic的方法,优雅而高效。

def remove_duplicate_1(lst):  # 精简逻辑版
    uni_lst = []
    for i in lst:
        if i not in uni_lst:
            uni_lst.append(i)
    return uni_lst

输出:

[1, 2, 3, 4, 5]
[1, 6, 5, 4, 3, 2]

2、集合版

利用集合元素不重复的特性来去重,更加快速,去重后可根据原始列表索引重新排序。

def remove_duplicate_2(lst):  # 集合版
    uni_lst = list(set(lst))
    uni_lst.sort(key=lst.index)
    return uni_lst

直接输出:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]

排序输出:

[1, 2, 3, 4, 5]
[1, 6, 5, 4, 3, 2]

3、字典版

利用 setdefault() 方法,若键不存在则添加。

def remove_duplicate_3(lst):  # 字典版
    dic = {}
    for index, key in enumerate(lst):
        dic.setdefault(key, index)
    uni_lst = list(dic.keys())
    return uni_lst

创建的字典:

{1: 0, 2: 1, 3: 3, 4: 4, 5: 6}
{1: 0, 6: 1, 5: 2, 4: 4, 3: 5, 2: 6}

输出:

[1, 2, 3, 4, 5]
[1, 6, 5, 4, 3, 2]

4、numpy 版

np.unique 方法返回去重后的 numpy 数组,默认按值排序,return_index 参数指定同时返回原始索引,之后可按原索引重新排序。最终返回类型为 numpy.ndarray ,可再套一个 list()

def remove_duplicate_4(lst):  # numpy版
    import numpy as np
    uni_lst, index = np.unique(lst, return_index=True)
    uni_lst = uni_lst[np.argsort(index)]
    return uni_lst

输出:

[1 2 3 4 5]
[1 6 5 4 3 2]

5、pandas 版

利用 Series 对象的 drop_duplicates 方法去重, keep 参数作用可指定去重后保留的元素顺位,如 first 即保留第一次出现的元素,操作较灵活但执行效率较低。

def remove_duplicate_5(lst):  # pandas版
    import pandas as pd
    s = pd.Series(lst)
    uni_lst = list(s.drop_duplicates(keep="first"))
    return uni_lst

输出:

[1, 2, 3, 4, 5]
[1, 6, 5, 4, 3, 2]

keep=“last” 时输出:

[1, 4, 3, 5, 2]
[5, 6, 4, 3, 2, 1]

5种方法效率比较

生成 10 万个 20以内的随机数用作测试列表,并自定义一个计时装饰器。

import random
import time

test_list = random.choices(range(20), k=100000)

def get_time(func):
    def wraper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 用时:{round(end_time-start_time,3)}秒")
        return result
    return wraper

装饰器用例:

@get_time
def remove_duplicate_1(lst):  # 精简逻辑版
    uni_lst = []
    for i in lst:
        if i not in uni_lst:
            uni_lst.append(i)
    return uni_lst

执行5种去重方法:

remove_duplicate_1(test_list)
remove_duplicate_2(test_list)
remove_duplicate_3(test_list)
remove_duplicate_4(test_list)
remove_duplicate_5(test_list)

输出:

remove_duplicate_1 用时:0.017秒
remove_duplicate_2 用时:0.002秒
remove_duplicate_3 用时:0.014秒
remove_duplicate_4 用时:0.157秒
remove_duplicate_5 用时:0.513秒

可见利用集合去重的执行效率最高(吊打其他)。这里是Seon塞翁,下篇再见。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 set() 函数将列表转换为集合,因为集合具有去重的功能,然后再将集合转换回列表即可去除重复元素。示例代码如下: ``` lst = [1, 2, 3, 2, 4, 1, 5, 3] lst = list(set(lst)) print(lst) ``` 输出结果为: ``` [1, 2, 3, 4, 5] ``` ### 回答2: Python 列表去重可以使用以下几方法: 1. 使用集合(set)方法:将列表转换为集合,由于集合中的元素是唯一的,重复的元素会被自动去除,然后再将集合转换回列表。例如: ```python lst = [1, 2, 2, 3, 4, 4, 5] lst = list(set(lst)) print(lst) ``` 输出结果为:[1, 2, 3, 4, 5] 2. 使用列表推导式方法:通过列表推导式的方式创建一个新列表,只包含原列表中的唯一元素。例如: ```python lst = [1, 2, 2, 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] 3. 使用循环方法:通过循环遍历原列表中的元素,将不重复的元素添加到一个新列表中。例如: ```python lst = [1, 2, 2, 3, 4, 4, 5] new_lst = [] for x in lst: if x not in new_lst: new_lst.append(x) print(new_lst) ``` 输出结果为:[1, 2, 3, 4, 5] 以上是三常见的去重方法,可以根据实际情况选择合适的方法。 ### 回答3: Python 列表去重可以通过多方式实现。以下是其中几常见的方法方法一:使用set()函数 利用set()函数可以将列表转换为集合,由于集合的特性是元素唯一,转换后的集合将自动去除重复元素,然后再将集合转换回列表。 示例代码: ``` lst = [1, 2, 3, 3, 4, 4, 5] lst = list(set(lst)) print(lst) # [1, 2, 3, 4, 5] ``` 方法二:使用列表推导式 使用列表推导式可以遍历列表,同时只添加未出现过的元素。 示例代码: ``` lst = [1, 2, 3, 3, 4, 4, 5] lst = list(set([x for x in lst])) print(lst) # [1, 2, 3, 4, 5] ``` 方法三:使用循环遍历 通过使用for循环遍历列表,判断元素是否已经存在于新列表中,如果不存在则添加到新列表中。 示例代码: ``` lst = [1, 2, 3, 3, 4, 4, 5] new_lst = [] for x in lst: if x not in new_lst: new_lst.append(x) print(new_lst) # [1, 2, 3, 4, 5] ``` 这些方法都可以有效地去重,并根据实际需求选择适合的方法来处理列表中的重复元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值