首页  >  文章  >  后端开发  >  Python中如何删除列表中的重复项?

Python中如何删除列表中的重复项?

PHPz
PHPz原创
2023-08-25 16:57:281995浏览

Python中如何删除列表中的重复项?

要从 Python 中的列表中删除重复项,我们可以使用本文中讨论的各种方法。

使用字典从列表中删除重复项

示例

在此示例中,我们将使用 OrderedDict 从列表中删除重复项 -

from collections import OrderedDict

# Creating a List with duplicate items
mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Remove duplicates from a list using dictionary
resList = OrderedDict.fromkeys(mylist)

# Display the List after removing duplicates
print("Updated List = ",list(resList))

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Jacob', 'Harry', 'Mark', 'Anthony']

使用列表理解从列表中删除重复项

示例

在此示例中,我们将使用列表理解从列表中删除重复项 

# Creating a List with duplicate items
mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Remove duplicates from a list using List Comprehension
resList = []
[resList.append(n) for n in mylist if n not in resList]
print("Updated List = ",resList)

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Jacob', 'Harry', 'Mark', 'Anthony']

使用 Set 从列表中删除重复项

示例

在此示例中,我们将使用 set() 方法从列表中删除重复项 -

# Creating a List with duplicate items
mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Remove duplicates from a list using Set
resList = set(mylist)
print("Updated List = ",list(resList))

输出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Anthony', 'Mark', 'Jacob', 'Harry']

以上是Python中如何删除列表中的重复项?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn