LoginSignup
29
32

More than 3 years have passed since last update.

Python 重複を削除する方法

Last updated at Posted at 2019-07-20

1.文字列から重複を削除。

1-1順序を気にしない場合
a_str = 'aaaffggaahhaaaa'
a_uniquie = ''.join(set(a_str))
print(a_uniquie)
# hafg ←実行する度に、毎回順序が変わります。

set()で、一意の文字の集合を作成。 "".join()は任意の順序で文字を文字列に結合。

1-2順序を気にする場合
from collections import OrderedDict
a_str = 'aaaffggaahhaaaa'
print(''.join(OrderedDict.fromkeys(a_str)))
# afgh ←順序を変えずに出力されます。

標準ライブラリcollectionsモジュールのOrderedDictを使用する。

2.リスト(orタプル)から重複を削除。

nums = [1, 2, 1, 2, 3, 2, 4, 5,]
nums_unique = list(set(nums))
print(nums_unique)
# [1, 2, 3, 4, 5]

set型は重複した要素をもたないデータ型であるため、
set()にリストを渡すと、一意な値のみを要素とするset型のオブジェクトを返す。
これをlist()で再びリストにする。
※タプルの場合はtuple()でタプルにすればよい。

以上です。

29
32
1

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
29
32