Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python数组去重

作者:涅盘の梦   发布日期:2025-11-06   浏览:11

# 示例代码: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)

解释说明:

  1. 使用集合(set)去重

    • 集合 set 是无序且不重复的元素集合。
    • 将列表转换为集合会自动去除重复元素,然后再将集合转换回列表。
    • 注意:集合是无序的,所以转换后的列表顺序可能与原列表不同。
  2. 使用字典(dict)去重并保持顺序

    • 从 Python 3.7 开始,字典保持插入顺序。
    • 使用 dict.fromkeys(arr) 可以创建一个字典,其中每个元素作为键,值为 None,然后将其转换回列表。
    • 这种方法可以去除重复元素并且保持原始顺序。

上一篇:python能干嘛

下一篇:python 字典操作

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站