Python去除列表中的重复元素

本文介绍了Python中五种不同的列表去重方法:使用集合、字典、列表推导、排序以及处理二元数组去重。每个方法都有其适用场景,例如集合操作快速但不保留原有顺序,而字典和排序方法则会改变原始顺序。此外,还提供了一个针对二维列表去重的例子。
摘要由CSDN通过智能技术生成

def func1(one_list):
    '''
    使用集合,个人最常用
    '''
    return list(set(one_list))


def func2(one_list):
    '''
    使用字典的方式
    '''
    return {}.fromkeys(one_list).keys()


def func3(one_list):
    '''
    使用列表推导的方式
    '''
    temp_list = []
    for one in one_list:
        if one not in temp_list:
            temp_list.append(one)
    return temp_list


def func4(one_list):
    '''
    使用排序的方法
    '''
    result_list = []
    temp_list = sorted(one_list)
    i = 0
    while i < len(temp_list):
        if temp_list[i] not in result_list:
            result_list.append(temp_list[i])
        else:
            i += 1
    return result_list

def func5(two_list):
    '''
    二元数组去重
    :param two_lsit:
    :return:
    '''
    temp_list = []

    for one in two_list:
        if one not in temp_list:
            temp_list.append(one)
    return temp_list

def func6(three_list):

    temp_list = []

    for one in three_list:
        if one not in temp_list:
            temp_one = []
            for i in one:
              if i not in temp_one:
                 temp_one.append(i)

            temp_list.append(temp_one)
        # two = {}.fromkeys(one).keys()
        # if two not in temp_list:
        #     temp_list.append(one)
    return temp_list

if __name__ == '__main__':
    one_list = [56, 7, 4, 23, 56, 9, 0, 56, 12, 3, 56, 34, 45, 5, 6, 56]
    print(func1(one_list))
    print(func2(one_list))
    print(func3(one_list))
    print(func4(one_list))
    print("-----------------------------------------")
    two_list = [['a','b'],[1,'a'],[1,'a']]
    print(func5(two_list))
    print("-----------------------------------------")
    three_list = [['a', 'b', 'a', 'b'], [1, 'a'], ['a',1] ,[1, 'a'] ]
    print(func6(three_list))

结果:

[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
dict_keys([56, 7, 4, 23, 9, 0, 12, 3, 34, 45, 5, 6])
[56, 7, 4, 23, 9, 0, 12, 3, 34, 45, 5, 6]
[0, 3, 4, 5, 6, 7, 9, 12, 23, 34, 45, 56]
-----------------------------------------
[['a', 'b'], [1, 'a']]
-----------------------------------------
[['a', 'b'], [1, 'a'], ['a', 1]]

最后一种,因为list是有序的,所以[1, ‘a’], [‘a’, 1]],是两种,如果大家有什么可以解决方法,可以评论留言。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值