0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python リストから順番を維持したまま重複を取り除く方法。

Posted at

Python3.7以降から使える方法です。

Python3.7からは辞書の順番が維持されるらしい。
##fromkeys()
以下のようにして辞書が生成できる。

入力 print(dict.fromkeys(["キー1", "キー2", "キー3"], "値"))
出力 {"キー1": "値", "キー2": "値", "キー3": "値"}

第二引数を指定しなければ値がNoneとなる。
print(dict.fromkeys(l))
{3: None, 2: None, 1: None, 5: None, 4: None}```

##list()
辞書を引数に渡すとkeyからリストを作る。

Keyは重複しない
##本題
入力

l = [3, 3, 2, 1, 5, 1, 4, 2, 3]
print(dict.fromkeys(l))
print(list(dict.fromkeys(l)))

出力

{3: None, 2: None, 1: None, 5: None, 4: None}`

[3, 2, 1, 5, 4]
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?