要从 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() 方法从列表中删除重复项 -
立即学习“Python免费学习笔记(深入)”;
# 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中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号