在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 = [x for i, x in enumerate(lst) if x not in lst[:i]]
print(unique_lst) 输出:[1, 2, 3, 4, 5]
3. 使用字典去重(利用字典键的唯一性):
lst = [1, 2, 3, 2, 4, 5, 4]
unique_lst = list(dict.fromkeys(lst))
print(unique_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. 使用`sort()`函数和`index`:
lst = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
lst = list(set(lst))
lst.sort(key=lst.index)
print(lst) 输出:[1, 2, 3, 10, 15, 20, 44, 56]
6. 循环遍历去重(保持原顺序):
lst = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
new_lst = []
for i in lst:
if i not in new_lst:
new_lst.append(i)
print(new_lst) 输出:[10, 1, 2, 3, 15, 20, 44, 56]
选择哪种方法取决于你的具体需求,例如是否需要保持素的原始顺序、列表的大小以及对性能的要求
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/117316.html