python从后面删除重复项_Python-从列表中删除重复项的方法

列表是一个重要的容器,几乎在日常编程和Web开发的每个代码中都使用列表,使用的次数更多,掌握它的需求也更多,因此必须了解其操作。从列表操作中删除重复项具有大量的应用程序,因此,其知识很好。

示例# using naive methods

# initializing list

test_list = [1, 3, 5, 6, 3, 5, 6, 1]

print ("The original list is : " +  str(test_list))

# using naive method to remove duplicated from list

res = []

for i in test_list:

if i not in res:

res.append(i)

# printing list after removal

print ("The list after removing duplicates : " + str(res))

# using list comprehension

# initializing list

test_list = [1, 3, 5, 6, 3, 5, 6, 1]

print ("The original list is : " +  str(test_list))

# using list comprehension to remove duplicated from list

res = []

[res.append(x) for x in test_list if x not in res]

# printing list after removal

print ("The list after removing duplicates : " + str(res))

# using set()# initializing list

test_list = [1, 5, 3, 6, 3, 5, 6, 1]

print ("The original list is : " +  str(test_list))

# using set() to remove duplicated from list

test_list = list(set(test_list))

# printing list after removal

print ("The list after removing duplicates : " + str(test_list))

# using list comprehension + enumerate()# initializing list

test_list = [1, 5, 3, 6, 3, 5, 6, 1]

print ("The original list is : " +  str(test_list))

# using list comprehension + enumerate() to remove duplicated from list

res = [i for n, i in enumerate(test_list) if i not in test_list[:n]]

# printing list after removal

print ("The list after removing duplicates : " + str(res))

# using collections.OrderedDict.fromkeys()

from collections import OrderedDict

# initializing list

test_list = [1, 5, 3, 6, 3, 5, 6, 1]

print ("The original list is : " +  str(test_list))

# using collections.OrderedDict.fromkeys() to remove duplicated from list

res = list(OrderedDict.fromkeys(test_list))

# printing list after removal

print ("The list after removing duplicates : " + str(res))

输出结果The original list is : [1, 3, 5, 6, 3, 5, 6, 1]

The list after removing duplicates : [1, 3, 5, 6]

The original list is : [1, 3, 5, 6, 3, 5, 6, 1]

The list after removing duplicates : [1, 3, 5, 6]

The original list is : [1, 5, 3, 6, 3, 5, 6, 1]

The list after removing duplicates : [1, 3, 5, 6]

The original list is : [1, 5, 3, 6, 3, 5, 6, 1]

The list after removing duplicates : [1, 5, 3, 6]

The original list is : [1, 5, 3, 6, 3, 5, 6, 1]

The list after removing duplicates : [1, 5, 3, 6]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值