在Python中,删除列表中的重复元素可以通过以下几种方法实现:
1. 使用集合(set):
lst = [1, 2, 3, 3, 4, 5, 5, 6]lst = list(set(lst))print(lst) 输出:[1, 2, 3, 4, 5, 6]
2. 使用列表推导式:
lst = [1, 2, 3, 3, 4, 5, 5, 6]new_lst = [][new_lst.append(x) for x in lst if x not in new_lst]print(new_lst) 输出:[1, 2, 3, 4, 5, 6]
3. 使用字典(dict.fromkeys):
mylist = ["a", "b", "a", "c", "c"]mylist = list(dict.fromkeys(mylist))print(mylist) 输出:['a', 'b', 'c']

4. 使用排序和遍历:
def deleteDuplicatedElementFromList(lst):lst.sort()length = len(lst)lastItem = lst[length - 1]for i in range(length - 2, -1, -1):currentItem = lst[i]if currentItem == lastItem:lst.remove(currentItem)else:lastItem = currentItemreturn lstlistA = ['python', '语', '言', '是', '一', '门', '动', '态', '语', '言']print(deleteDuplicatedElementFromList(listA)) 输出:['python', '语', '言', '是', '一', '门', '动', '态']
5. 使用列表理解式:
l1 = ['b', 'c', 'd', 'b', 'c', 'a', 'a']l2 = [][l2.append(i) for i in l1 if not i in l2]print(l2) 输出:['b', 'c', 'd', 'a']
以上方法各有优缺点,选择哪一种取决于你的具体需求和应用场景。需要注意的是,使用集合去重会丢失原始列表的顺序,如果需要保持顺序,可以使用排序加遍历的方法或者列表推导式
