0
0

More than 3 years have passed since last update.

部分集合のリストに対応する元の集合リストのindexを取り出す。

Posted at

ある二つのリスト(A, B)を用意する。ここで$B\subset A$である。
部分集合Bに対応するAのindexを取り出したい。

つまり

A = [1\sim 100の整数のリスト]\\
B = [1\sim 100の偶数のリスト]\\

\Longrightarrow index = [1, 3, 5, 7..., 99]

このようなindexを取得する。

実装

A = list(range(1, 101))

B = list(range(2, 102, 2))

部分集合Bに対応するAの要素にTrueを返す関数がNumpyにある。

import numpy as np

isin = np.isin(A, B)
print(isin)
#array([False,  True, False,  True, False,  True, False,  True, False...
print(len(isin) == len(A))
#True

また、Trueの要素のindexを返す関数もNumpyにあった。

index = list(np.where(isin))[0]
print(index)
#array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33...

実装できた。

実践

ランダムな数字を与えたAとそこからランダムに要素を取得したBを用意する。


A = random.sample(range(1, 100), k=5)
B = random.sample(A, 3)

print(A)
#[37, 24, 76, 55, 52]
print(B)
#[55, 76, 37]

index = list(np.where(np.isin(A, B)))[0]
print(index)
#array([0, 2, 3])

ランダムでも取得できた。

今後

indexを取得できたが、それはソートされたものであった。つまり、Bの最初の要素は、Aの何番目の要素であるようにBの順番を考慮したindexは取得できていない。for文で一つ一つ確認することはできるが、大きい長さのA、Bの場合だと計算量がとても大きくなってしまう。そのため別な方法を考えなければいけないだろう。

0
0
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
0