# 示例代码:Python数组去重
# 方法1:使用集合(set)去重
def remove_duplicates_with_set(arr):
# 集合会自动去除重复元素
return list(set(arr))
# 方法2:使用字典(dict)从值去重并保持顺序
def remove_duplicates_with_dict(arr):
# 字典的键是唯一的,因此可以用来去重
# 从Python 3.7开始,字典保持插入顺序
return list(dict.fromkeys(arr))
# 示例数组
arr = [1, 2, 2, 3, 4, 4, 5]
# 调用方法1
result1 = remove_duplicates_with_set(arr)
print("使用集合去重:", result1)
# 调用方法2
result2 = remove_duplicates_with_dict(arr)
print("使用字典去重:", result2)
使用集合(set)去重:
set 是无序且不重复的元素集合。使用字典(dict)去重并保持顺序:
dict.fromkeys(arr) 可以创建一个字典,其中每个元素作为键,值为 None,然后将其转换回列表。上一篇:python能干嘛
下一篇:python 字典操作
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站