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

python 去重

作者:身后错过痛过漫长情节ゝ   发布日期:2025-06-08   浏览:31

# 示例代码:使用集合去重列表中的元素

def remove_duplicates(input_list):
    # 使用集合去除重复元素,因为集合中的元素是唯一的
    unique_elements = list(set(input_list))
    return unique_elements

# 示例用法
example_list = [1, 2, 2, 3, 4, 4, 5]
result = remove_duplicates(example_list)
print(result)  # 输出: [1, 2, 3, 4, 5]

# 注意:使用 set 去重会打乱原始顺序,如果需要保持顺序,可以使用以下方法

def remove_duplicates_preserve_order(input_list):
    # 使用字典的键来去重并保持顺序(Python 3.7+)
    unique_elements = list(dict.fromkeys(input_list))
    return unique_elements

# 示例用法
ordered_example_list = [1, 2, 2, 3, 4, 4, 5]
ordered_result = remove_duplicates_preserve_order(ordered_example_list)
print(ordered_result)  # 输出: [1, 2, 3, 4, 5]

上一篇:python字符串比较

下一篇:python 单例

大家都在看

python时间格式

python ord和chr

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

python中list代表什么

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

Laravel 中文站