如何从Python列表中删除重复项
了解如何从Python中的List中删除重复项技巧。
实例
从列表中删除任何重复项:
mylist = ["a","b","a","c","c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
实例说明
首先,我们有一个包含重复项的List:
具有重复项的列表
mylist = ["a","b","a","c","c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
使用列表项作为键创建字典。这将自动删除任何重复项,因为词典不能有重复的键。
创建一个字典
mylist = ["a","b","a","c","c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
然后,将字典转换回列表:
转换为列表
mylist = ["a","b","a","c","c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
现在我们有一个没有任何重复的List,它与原始List具有相同的顺序。
打印列表以演示结果
打印列表
mylist = ["a","b","a","c","c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
创建一个函数
如果您希望有一个可以发送列表的函数,并且无需重复,则可以创建一个函数并插入上面示例中的代码。
实例
def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)
实例说明
创建一个以List作为参数的函数。
#创建一个函数
def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)
使用此List项作为键创建字典。
#创建一个字典
defmy_function(x):
returnlist(dict.fromkeys(x))
mylist =my_function(["a","b","a","c","c"])
print(mylist)
将字典转换为列表。
#转换为列表
defmy_function(x):
returnlist(dict.fromkeys(x))
mylist =my_function(["a","b","a","c","c"])
print(mylist)
返回列表
#返回列表
defmy_function(x):
returnlist(dict.fromkeys(x))
mylist =my_function(["a","b","a","c","c"])
print(mylist)
使用列表作为参数调用该函数:
defmy_function(x):
returnlist(dict.fromkeys(x))
mylist = my_function(["a","b","a","c","c"])
print(mylist)
打印结果:
defmy_function(x):
returnlist(dict.fromkeys(x))
mylist = my_function(["a","b","a","c","c"])
print(mylist)