Python 教程
/ 刪除列表重復(fù)項
刪除列表重復(fù)項
實例
從列表中刪除任何重復(fù)項:
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
運行實例
實例解釋
首先,我們有一個包含重復(fù)項的 List:
包含重復(fù)項的列表
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
使用列表項作為鍵創(chuàng)建字典。這將自動刪除任何重復(fù)項,因為詞典不能有重復(fù)的鍵。
創(chuàng)建字典
mylist = ["a", "b", "a", "c", "c"] mylist = list( dict.fromkeys(mylist) ) print(mylist)
然后,將字典轉(zhuǎn)換回列表:
轉(zhuǎn)換為 List
mylist = ["a", "b", "a", "c", "c"] mylist = list( dict.fromkeys(mylist) ) print(mylist)
現(xiàn)在我們有一個沒有任何重復(fù)的 List,它與原始 List 擁有相同的順序。
打印列表以演示結(jié)果:
打印 List
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
創(chuàng)建函數(shù)
如果您希望有一個函數(shù)可以發(fā)送列表,然后它們返回的無重復(fù)項,則可以創(chuàng)建函數(shù)并插入上例中的代碼。
實例
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
運行實例
例子解釋
創(chuàng)建一個以 List 作為參數(shù)的函數(shù)。
創(chuàng)建函數(shù)
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
使用此 List 項作為鍵創(chuàng)建字典。
創(chuàng)建字典
def my_function(x): return list( dict.fromkeys(x) ) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
將字典轉(zhuǎn)換為列表:
轉(zhuǎn)換為列表
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)
使用列表作為參數(shù)來調(diào)用該函數(shù):
調(diào)用函數(shù)
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
打印結(jié)果:
打印結(jié)果
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)