威凡网全力打造:网页编程、软件开发编程、平面设计、服务器端开发、操作系统等在线学习平台!学编程,上威凡网!
python教程>> python基础 python进阶 python高级 python技巧
当前位置:首页 > python教程 > python基础
上一节 下一节
 如何从 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)

然后,将字典转换回列表:

转换为 list
mylist = ["a", "b", "a", "c", "c"]
mylist = list( dict.fromkeys(mylist) ) 
print(mylist)

现在我们有一个没有任何重复的 list,它与原始 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 项作为键创建字典。

创建字典
def my_function(x):
  return list( dict.fromkeys(x) )

mylist = my_function(["a", "b", "a", "c", "c"])

print(mylist)

将字典转换为列表:

转换为列表
def my_function(x):
  return list( dict.fromkeys(x) ) 

mylist = my_function(["a", "b", "a", "c", "c"])

print(mylist)

返回列表:

返回列表
def my_function(x):
  return list(dict.fromkeys(x))

mylist = my_function(["a", "b", "a", "c", "c"])

print(mylist)

使用列表作为参数来调用该函数:

调用函数
def my_function(x):
  return list(dict.fromkeys(x))

mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)

打印结果:

打印结果
def my_function(x):
  return list(dict.fromkeys(x))

mylist = my_function(["a", "b", "a", "c", "c"])print(mylist) 

申明:本教程内容由威凡网编辑整理并提供IT程序员分享学习,如文中有侵权行为,请与站长联系(QQ:254677821)!
上一节 下一节
相关教程  
其他教程  
python基础
python进阶
python高级
python技巧

违法和不良信息举报中心】邮箱:254677821@qq.com
Copyright©威凡网 版权所有 苏ICP备2023020142号
站长QQ:254677821