python去重函数_python去重保留唯一一个值

python去重函数_python去重保留唯一一个值在 Python 中 去重列表素是一个常见的操作 以下是几种常用的去重方法 1 使用 set 函数 pythonlst 1 2 2 3 4 4 5 unique lst list set lst print unique lst 输出 1 2 3 4 5 2 使用列表推导式 pythonlst 1 2 2 3 4

在Python中,去重列表素是一个常见的操作。以下是几种常用的去重方法:

1. 使用`set()`函数:

```python

lst = [1, 2, 2, 3, 4, 4, 5]

unique_lst = list(set(lst))

print(unique_lst) 输出:[1, 2, 3, 4, 5]

2. 使用列表推导式:```python

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. 使用`for`循环和列表来保持原始顺序:

```python

lst = [1, 2, 2, 3, 4, 4, 5]

unique_lst = []

for item in lst:

if item not in unique_lst:

unique_lst.append(item)

print(unique_lst) 输出:[1, 2, 3, 4, 5]

4. 使用`dict.fromkeys()`方法:```python

lst = [1, 2, 2, 3, 4, 4, 5]

unique_lst = list(dict.fromkeys(lst))

print(unique_lst) 输出:[1, 2, 3, 4, 5]

5. 使用`itertools.groupby()`方法(需要对列表进行排序):

```python

import itertools

lst = [1, 2, 2, 3, 4, 4, 5]

lst.sort()

unique_lst = [key for key, group in itertools.groupby(lst)]

print(unique_lst) 输出:[1, 2, 3, 4, 5]

以上方法各有优缺点,选择哪一种取决于具体的应用场景和性能要求。需要注意的是,使用`set()`函数去重会丢失原始列表的顺序,而使用列表推导式、`for`循环和`dict.fromkeys()`方法可以保持原始顺序。如果需要保持顺序并且列表很长,可能需要考虑性能优化。

编程小号
上一篇 2026-03-09 19:16
下一篇 2026-03-09 19:12

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/76374.html