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)