0
点赞
收藏
分享

微信扫一扫

python常用功能模块

程序员知识圈 2022-04-23 阅读 62
python

1、从 List 中删除重复元素的N种方法

# 方式1:遍历列表,生成新列表保存不重复的元素
def duplicate_removal(list_name):
    """
    列表去重
    :param list_name: 一个有重复元素的列表
    :return: 去重的列表
    """
    # 方式1:遍历复杂模式
    new_list = []
    for i in list_name:
        if i not in new_list:
            new_list.append(i)
    return new_list
    # 方式2:列表推导式模式
    [new_list.append(x) for x in list_name if x not in new_list]
    return new_list
    # 方式3:使用set(),最流行。缺点:使用过后列表中元素的顺序不再与原来的一致了。
    return list(set(list_name))
    # 方式4:在列表推导式的基础上利用枚举来去除重复元素。通过检查元素是否已经在列表中存在从而将其略过。
    new_list = [i for n, i in enumerate(list_name) if i not in list_name[:n]]
    return new_list
    # 方式5:最快的方法。它先是将列表中的重复项移除并返回一个字典,最后转换成列表。这种方法对于字符串也可以进行处理。
    from collections import OrderedDict
    new_list = list(OrderedDict.fromkeys(list_name))
    return new_list

# 还有其它方法实现,但有点复杂就不写了。
举报

相关推荐

0 条评论