使用字典从列表中删除重复项 示例 在此示例中,我们将使用 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中如何删除列表中的重复项?的详细内容。
