# 示例代码:Python 列表去重
# 方法1:使用集合(set)
def remove_duplicates_with_set(lst):
# 集合会自动去除重复元素,然后将其转换回列表
return list(set(lst))
# 方法2:使用字典(dict)保持顺序(从 Python 3.7 开始,字典保持插入顺序)
def remove_duplicates_with_dict(lst):
# 字典的键是唯一的,因此可以用来去重,并且保留原始顺序
return list(dict.fromkeys(lst))
# 方法3:使用列表推导式和 in 操作符
def remove_duplicates_with_list_comprehension(lst):
result = []
[result.append(i) for i in lst if i not in result]
return result
# 示例列表
example_list = [1, 2, 2, 3, 4, 4, 5]
# 调用方法并打印结果
print(remove_duplicates_with_set(example_list)) # 输出: [1, 2, 3, 4, 5] (顺序可能不同)
print(remove_duplicates_with_dict(example_list)) # 输出: [1, 2, 3, 4, 5] (保持顺序)
print(remove_duplicates_with_list_comprehension(example_list)) # 输出: [1, 2, 3, 4, 5] (保持顺序)
上一篇:complex函数python
下一篇:python删除文件夹
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站