列表中去除重复项的几种方法和Python的set()函数
在实际编程中,常常需要对列表中的重复项进行处理,以达到更好的效果。下面就介绍几种去重的方法和Python中的set()函数。
1.使用循环+判断:
这是常用的一种去重方法。通过遍历列表,依次比较每个元素是否与已经存在的不重复元素相等,如果不相等就添加到不重复元素中。具体实现如下:
def del_duplicate(lst):
no_duplicate = []
for item in lst:
if item not in no_duplicate:
no_duplicate.append(item)
return no_duplicate
2.使用set:
set是Python内置的一种数据结构,它不允许出现重复元素。因此,将列表转换为set类型,再转换回来,就可以达到去重的目的了。具体实现如下:
def del_duplicate(lst):
return list(set(lst))
3.使用字典:
利用字典的key不重复的特性进行去重,重复的元素会被覆盖,最后将字典的key转成新列表即可。具体实现如下:
def del_duplicate(lst):
no_duplicate = {}
for item in lst:
no_duplicate[item] = 1
return list(no_duplicate.keys())
4.使用列表推导式:
列表推导式可以快速地生成新列表,过程中可以加入去重操作,具体实现如下:
def del_duplicate(lst):
return [] if not lst else [lst[0]] + [lst[i] for i in range(1, len(lst)) if lst[i] != lst[i-1]]
以上是常用的几种列表去重方法,其中set()函数比较简单并且效率较高。使用时可以按需选择。
