如何從 Python 列表中刪除重複項
瞭解如何在 Python 中從列表中刪除重複項。
示例
移除列表中的任何重複項
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)
然後,將字典轉換回列表
轉換為列表
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)
建立函式
如果你想建立一個函式,可以將列表作為引數傳入,並返回無重複項的列表,可以插入上面的示例程式碼。
示例
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)
呼叫函式,並將一個列表作為引數傳遞
呼叫函式
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)