Pythonでリストの重複要素アレコレ

Python小ネタです.
リストの重複要素についてコネコネすることがあったので,忘れないようにメモです.

重複要素を除外したリストを取得

list = ["a", "b", "c", "b", "d", "a", "b", "e"]
res = set(list)
print(res)
> {'a', 'b', 'c', 'e', 'd'}

重複要素を除外したリストを取得(順番を守りたい場合)

↑のだと順番がおかしくなっちゃうので,順番を保持したい場合は以下のように.

list = ["a", "b", "c", "b", "d", "a", "b", "e"]
res = sorted(set(list), key=list.index)
print(res)
> ['a', 'b', 'c', 'd', 'e']

重複要素のみを取得

list = ["a", "b", "c", "b", "d", "a", "b", "e"]
res = [e for e in set(list) if list.count(e) > 1]
print(res)
> ['a', 'b']

順番を守りたい場合はsortedを使えばOKです~

重複要素+その数を取得

list = ["a", "b", "c", "b", "d", "a", "b", "e"]
res = [[e, list.count(e)] for e in set(list) if list.count(e) > 1]
print(res)
> [['a', 2], ['b', 3]]

2重リストの重複要素のみを取得

タスクを分解します.
・2重リストを1重リストにする
・重複要素の取り出し

lists = [["a", "b", "c"], ["b", "d"], ["a", "b", "e"], ["f", "f", "a"]]
list = [e for list in lists for e in list]            # 2重リストを1重リストに
res = set([e for e in list if list.count(e) > 1])     # 重複要素の取り出し
print(res)
> {'a', 'b', 'f'}

順番を守りたい場合h・・・(以下ry)

無いと思いますが,ワンライナーでやりたい場合はこちら.

lists = [["a", "b", "c"], ["b", "d"], ["a", "b", "e"], ["f", "f", "a"]]
res = set([e for list in lists for e in list if any(e in _list for _list in lists if not _list is list) or any(_list.count(e) > 1 for _list in lists if _list is list)])
print(res)
> {'a', 'b', 'f'}

これ,ワンライナーが過ぎますね…
ワンライナーでいい方法あったら教えてください~

シェアする

  • このエントリーをはてなブックマークに追加

フォローする