0
0

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 5 years have passed since last update.

Python で値の重複を含むリストを値の一意なリストへ[スニペット的備忘録的に]

Posted at

既存のリスト(一部の値が重複):

['a','a','b','d','d','c','e','c','a']

これを値の一意なリストにしたい:

['a','b','d','c','e']
>>> list1 = ['a','a','b','d','d','c','e','c','a']
>>> list2 = ['dummy'] # 最初にループさせるためのダミー要素.最後に削除
>>> for i in list1:
...     count = 0
...     for j in list2:
...         if j == i: # 作成中の一意リストは重複なく作られているのでここの条件 合致は 0回か 1回
...             count += 1
...     if count == 0: # count がとり得る値は 0 か 1
...         list2.append(i)
... 
>>> list2 = list2[1:] # ダミー要素の削除
>>> print(list2)
['a', 'b', 'd', 'c', 'e']

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?