LoginSignup
14
7

More than 5 years have passed since last update.

PythonのListに含まれる全ての要素がもう一つのListに含まれるかの検証方法

Last updated at Posted at 2017-12-23

はじめに

list1 = [0, 1, 2]
list2 = [4, 2, 5, 6, 12, 1, 9, 0]

上記のようにlist1の要素全てがlist2に含まれるかを検証して真偽値を返す必要があったのでやってみます。

方法1

最初に以下のような関数を思いつきました。

def list_check1(list1, list2):
    count = 0
    for element in list1:
        if element in list2:
            count += 1
        if len(list1) == count:
            return True
    return False

これでいいのですが、list1の要素数が増えるとすごく遅くなってしまいます。

list_check1.py
import time

def list_check1(list1, list2):
    count = 0
    for element in list1:
        if element in list2:
            count += 1
        if len(list1) == count:
            return True
    return False

start = time.time()
list1 = [i for i in range(10000)]
list2 = [i for i in range(100000)]
print(list_check1(list1, list2))
print(time.time()-start)
$ python list_check1.py
True
0.7270619869232178

方法2

Setオブジェクトにはsetの全ての要素がotherに含まれるか判定するissubset(other)メソッドがあるので、一度ListをSetに変換して判定してみます。

list_check2.py
import time

def list_check2(list1, list2):
    return set(list1).issubset(list2)

start = time.time()
list1 = [i for i in range(10000)]
list2 = [i for i in range(100000)]
print(list_check2(list1, list2))
print(time.time()-start)
$ python list_check2.py
True
0.012912750244140625

list_check1と比べてかなり速くなりました。

14
7
3

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