Python列表去重方法

方法一:使用内置set方法来去重

>>> lst1=[2,3,41,2,4,3,4]
>>> lst2=list(set(lst1))
>>> print(lst2)
[41, 2, 3, 4]

方法二:使用字典中fromkeys()的方法来去重

>>> lst1=[2,3,41,2,4,3,4]
>>> lst2={}.fromkeys(lst1).keys()
>>> print(lst2)
dict_keys([2, 3, 41, 4])

方法三:使用常规方法来去重

[root@localhost ~]# cat listuniq.py 
lst1 = [2,3,41,2,4,3,4]
temp = []
for item in lst1:
    if not item in temp:
        temp.append(item)    
print(temp)

[root@localhost ~]# python listuniq.py 
[2, 3, 41, 4]

方法四: 使用列表推导来去重

>>> lst1=[2,3,41,2,4,3,4]
>>> temp = []
>>> [temp.append(i) for i in lst1 if not i in temp]
[None, None, None, None]
>>> print(temp)
[2, 3, 41, 4]

方法五: 使用sorted函数来去重

>>> lst1=[2,3,41,2,4,3,4]
>>> lst2 = sorted(set(lst1), key=lst1.index)
>>> print(lst2)
[2, 3, 41, 4]

备注: 前面的几种方法,有几种是不能保证其顺序的,比如用set()函数来处理!

如果要删除列表列表中的重复项,则同样可以用下面的几种方法来处理

>>> # 方法一:
>>> data = [2, 1, 3, 4, 1]
>>> [item for item in data if data.count(item) == 1]
[2, 3, 4]
>>> # 方法二:
>>> data = [2, 1, 3, 4, 1]
>>> list(filter(lambda x:data.count(x) == 1, data))
[2, 3, 4]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值