如何從 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)