python列表怎么删除重复元素_python去除字符串重复元素

python列表怎么删除重复元素_python去除字符串重复元素在 Python 中 删除列表中的重复素可以通过以下几种方法实现 1 使用 set 函数 pythonlst 1 2 2 3 4 4 5 lst list set lst print lst 输出 1 2 3 4 5 2 使用列表推导式 pythonlst 1 2 2 3 4 4 5 lst list i

在Python中,删除列表中的重复素可以通过以下几种方法实现:

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

python

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

lst = list(set(lst))

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

2. 使用列表推导式:

python

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

lst = list({i for i in lst})

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

3. 使用循环遍历:

python

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

new_lst = []

for i in lst:

if i not in new_lst:

new_lst.append(i)

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

4. 使用`filter()`函数:

python

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

lst = list(filter(lambda x: lst.count(x) == 1, lst))

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

5. 使用`dict.fromkeys()`方法:

python

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

lst = list(dict.fromkeys(lst))

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

6. 使用排序和删除方法:

python

def delete_duplicated_elements(lst):

lst.sort()

length = len(lst)

last_item = lst[length - 1]

for i in range(length - 2, -1, -1):

current_item = lst[i]

if current_item == last_item:

lst.remove(current_item)

else:

last_item = current_item

return lst

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

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

7. 使用`numpy.unique()`方法(适用于数值列表):

python

import numpy as np

lst = [1, 1, 2, 3, 4, 6, 9, 6, 2, 2]

lst = np.unique(lst).tolist()

print(lst) 输出:[1, 2, 3, 4, 6, 9]

以上方法各有优缺点,选择哪一种取决于你的具体需求,比如是否需要保持原始列表中素的顺序,以及列表中素的数据类型。

编程小号
上一篇 2025-06-15 11:56
下一篇 2026-05-10 09:53

相关推荐

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