Python 如何删除一个列表(list)中的重复元素【面试题详解】

今天爱分享给大家带来Python 如何删除一个列表(list)中的重复元素【面试题详解】,希望能够帮助到大家。

删除列表中重复的元素有多种方式,下面介绍五种删除的方法。

方法一:使用集合 (set) 的方式

elements = ["a", "a", "b", "c", "c", "b", "d"]
e = list(set(elements))
print(e)

 
这种方法利用 set 中的元素不可重复的特性去重。除此之外,如果要保持列表元素的原来顺序,那么可以利用 list 类的 sort 方法:

elements = ["a", "a", "b", "c", "c", "b", "d"]
e = list(set(elements))
e.sort(key=elements.index)
print(e)  # ['a', 'b', 'c', 'd']

方法二:使用字典的方式,利用字典 key 的唯一性

# 使用字典的方式,利用字典 key 的唯一性
elements = ["a", "a", "b", "c", "c", "b", "d"]
# e = list({}.fromkeys(elements))
e = list({}.fromkeys(elements).keys())
print(e)  # ['a', 'b', 'c', 'd']

这种方法利用字典的键值不能重复的特性来去重。其中,Python 函数 dict.fromkeys(seq[.value]) 用于创建一个新字典,以序列 seq 中元素做字典的值,value 为字典所有键对应的初始值,如下所示:

方法三:列表推导的方式

elements = ["a", "a", "b", "c", "c", "b", "d"]
e = []
for i in elements:
    if i not in e:
        e.append(i)
print(e)

方法四:count计数

elements = ["a", "a", "b", "c", "c", "b", "d"]
n = 0
while n < len(elements):
    if elements.count(elements[n]) > 1:
        elements.remove(elements[n])
        continue
    n += 1
print(elements)  # ['a', 'c', 'b', 'd']

方法五:reduce 函数

from functools import reduce

elements = ["a", "a", "b", "c", "c", "b", "d"]
v = reduce(lambda x, y: x if y in x else x + [y], [[]] + elements)
print(v)  # ['a', 'b', 'c', 'd']

原文链接:https://blog.itblood.com/1489.html,转载请注明出处。
0
森林之庭~小镇牧场生活~V1.2.2 内嵌AI汉化版[更新][750M] [精品RPG/汉化]
森林之庭~小镇牧场生活~V1.2.2 内嵌AI汉化版[更新][750M] [精品RPG/汉化]
3分钟前 有人购买 去瞅瞅看

站点公告

显示验证码
没有账号?注册  忘记密码?