手册目录
Python 教程
Python 机器学习
Python MySQL
从列表中删除任何重复项:
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 项作为键创建字典。
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)
相关视频
科技资讯
24小时阅读榜
1
2
3
4
5
6
7
8
9
10
精品课程
共5课时 | 17.4万人学习
共49课时 | 78.2万人学习
共29课时 | 62.5万人学习
共25课时 | 39.7万人学习
共43课时 | 73.8万人学习