在Python中,去重可以通过多种方法实现,以下是几种常见的方法:
1. 使用`set()`函数:
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
print(unique_lst) 输出:[1, 2, 3, 4, 5]
2. 使用列表推导式:
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = [i for i in lst if i not in lst[:]]
print(unique_lst) 输出:[1, 2, 3, 4, 5]
3. 使用`for`循环遍历:
lst = [1, 2, 2, 3, 4, 4, 5]
new_lst = []
for i in lst:
if i not in new_lst:
new_lst.append(i)
print(new_lst) 输出:[1, 2, 3, 4, 5]
4. 使用`filter()`函数:
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(filter(lambda x: lst.count(x) == 1, lst))
print(unique_lst) 输出:[1, 2, 3, 4, 5]
5. 使用`OrderedDict`从`collections`模块:
from collections import OrderedDict
lst = [1, 5, 2, 1, 10]
unique_lst = list(OrderedDict.fromkeys(lst))
print(unique_lst) 输出:[1, 5, 2, 10]
以上方法都可以实现列表去重,你可以根据具体需求选择合适的方法。需要注意的是,使用`set()`函数去重会改变列表中元素的原始顺序,如果需要保持原始顺序,可以使用列表推导式或`for`循环遍历的方法