在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 OrderedDictlst = [1, 5, 2, 1, 10]unique_lst = list(OrderedDict.fromkeys(lst))print(unique_lst) 输出:[1, 5, 2, 10]
以上方法都可以实现列表去重,你可以根据具体需求选择合适的方法。需要注意的是,使用`set()`函数去重会改变列表中素的原始顺序,如果需要保持原始顺序,可以使用列表推导式或`for`循环遍历的方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/82252.html