HOWTO · Python

Python 목록에 값이 빠른지 확인하는 방법

이 튜토리얼은 파이썬 목록에 값이 존재하는지 확인한 다음 성능을 비교하는 다양한 방법을 보여줍니다.

이 페이지의 내용

파이썬 목록에 값이 있는지 확인하고 성능을 비교하는 다양한 방법을 소개합니다.

방법은 다음과 같습니다.

  1. 회원 확인 방법-in 방법 값이 있는지 확인
  2. 목록을 set으로 변환 한 다음 멤버쉽 확인 방법 in 을 사용하십시오.

파이썬리스트에 존재하는 값을 확인하는 in 메소드

in 은 파이썬리스트, 세트, ​​딕셔너리 또는 기타 반복 가능한 파이썬 객체에서 멤버쉽 확인을 수행하는 올바른 방법입니다.

>>> testList = [1, 2, 3, 4]
>>> 2 in testList
True
>>> 6 in testList
False

파이썬에서 목록을 설정하고 멤버쉽 확인으로 변환하십시오

목록 크기가 커지면 특히 목록에 중복 요소가있는 경우 멤버십 체크인 목록이 비효율적 일 수 있습니다.

이 시나리오에서 Python 세트는 고유 한 값만 포함하기 때문에 멤버십 확인을 수행하는 데 더 나은 데이터 유형입니다.

리스트와 세트 멤버쉽 체크의 성능 비교

4 가지 상황에서 성능 차이를 비교해 보겠습니다.

  1. 원래 목록에는 고유 한 값이 있으며 확인 된 값은 목록에 있습니다
  2. 원래 목록에는 고유 한 값이 있으며 확인 된 값은 목록에 없습니다
  3. 원래 목록에 중복 값이 ​​있고 확인 된 값이 목록에 있습니다.
  4. 원본 목록에 중복 값만 있고 확인 된 값이 목록에 없습니다.

원래 목록에는 고유 한 값만 있으며 확인 된 값은 목록에 있습니다

목록에 값이 존재하는지 여부-목록에 고유 한 값과 확인할 값이 있습니다

from itertools import chain
import perfplot
import numpy as np


def setupTest(n):
    a = np.arange(n)
    np.random.shuffle(a)
    randomlist = a[: n // 2].tolist()
    randomvalue = randomlist[len(randomlist) // 2]
    return [randomlist, randomvalue]


def inListMethod(L):
    x, y = L
    return y in x


def inSetMethod(L):
    x, y = L
    x = set(x)
    return y in x


perfplot.show(
    setup=setupTest,
    kernels=[inListMethod, inSetMethod],
    labels=["in list", "in set"],
    n_range=[2 ** k for k in range(1, 20)],
    xlabel="Data Length",
    title="unique values in list and to-be-checked value exists in the list",
    logx=True,
    logy=True,
)

원래 목록에는 고유 한 값만 있으며 확인 된 값은 목록에 없습니다

python-값이 목록에 있는지 여부-목록의 고유 값 및 확인할 값이 목록에 없습니다

from itertools import chain
import perfplot
import numpy as np


def setupTest(n):
    a = np.arange(n)
    np.random.shuffle(a)
    randomlist = a[: n // 2].tolist()
    randomvalue = n + 1
    return [randomlist, randomvalue]


def inListMethod(L):
    x, y = L
    return y in x


def inSetMethod(L):
    x, y = L
    x = set(x)
    return y in x


perfplot.show(
    setup=setupTest,
    kernels=[inListMethod, inSetMethod],
    labels=["in list", "in set"],
    n_range=[2 ** k for k in range(1, 20)],
    xlabel="Data Length",
    title="unique values in list and to-be-checked value does not exist in the list",
    logx=True,
    logy=True,
)

원래 목록에 중복 값이 ​​있고 확인 된 값이 목록에 있습니다

파이썬이 목록에 값이 있는지 여부-목록에 중복 값과 확인할 값이 목록에 있습니다

from itertools import chain
import perfplot
import numpy as np


def setupTest(n):
    a = np.arange(n)
    np.random.shuffle(a)
    randomlist = np.random.choice(n, n // 2).tolist()
    randomvalue = randomlist[len(randomlist) // 2]
    return [randomlist, randomvalue]


def inListMethod(L):
    x, y = L
    return y in x


def inSetMethod(L):
    x, y = L
    x = set(x)
    return y in x


perfplot.show(
    setup=setupTest,
    kernels=[inListMethod, inSetMethod],
    labels=["in list", "in set"],
    n_range=[2 ** k for k in range(2, 20)],
    xlabel="Data Length",
    title="duplicate values in list and to-be-checked value exists in the list",
    logx=True,
    logy=True,
)

원래 목록에 중복 값만 있고 확인 된 값이 목록에 없습니다

파이썬이 목록에 값이 존재하는지 여부-목록에 중복 값과 확인할 값이 목록에 존재하지 않습니다

from itertools import chain
import perfplot
import numpy as np


def setupTest(n):
    a = np.arange(n)
    np.random.shuffle(a)
    randomlist = np.random.choice(n, n // 2).tolist()
    randomvalue = n + 1
    return [randomlist, randomvalue]


def inListMethod(L):
    x, y = L
    return y in x


def inSetMethod(L):
    x, y = L
    x = set(x)
    return y in x


perfplot.show(
    setup=setupTest,
    kernels=[inListMethod, inSetMethod],
    labels=["in list", "in set"],
    n_range=[2 ** k for k in range(2, 20)],
    xlabel="Data Length",
    title="duplicate values in list and to-be-checked value does not exist in the list",
    logx=True,
    logy=True,
)

성능 비교 결론

Python set 의 멤버쉽 확인이 Python list 의 멤버쉽보다 빠르지 만 list 또는 set의 변환은 시간이 걸립니다. 따라서 주어진 데이터가 Python 목록 인 경우 먼저 목록을 set 으로 변환 한 다음 set 에서 멤버십 검사를 수행하면 성능상의 이점이 없습니다.

값이 목록에 존재하는지 여부-개요

from itertools import chain
import perfplot
import numpy as np


def setupTest(n):
    a = np.arange(n)
    np.random.shuffle(a)
    unique_randomlist = a[: n // 2].tolist()
    duplicate_randomlist = np.random.choice(n, n // 2).tolist()
    existing_randomvalue = unique_randomlist[len(unique_randomlist) // 2]
    nonexisting_randomvalue = n + 1
    return [
        unique_randomlist,
        duplicate_randomlist,
        existing_randomvalue,
        nonexisting_randomvalue,
    ]


def inListMethod_UniqueValue_ValueExisting(L):
    u, d, ex, ne = L
    return ex in u


def inListMethod_DuplicateValue_ValueExisting(L):
    u, d, ex, ne = L
    return ex in d


def inListMethod_UniqueValue_ValueNotExisting(L):
    u, d, ex, ne = L
    return ne in u


def inListMethod_DuplicateValue_ValueNotExisting(L):
    u, d, ex, ne = L
    return ne in d


def inSetMethod_UniqueValue_ValueExisting(L):
    u, d, ex, ne = L
    u = set(u)
    return ex in u


def inSetMethod_DuplicateValue_ValueExisting(L):
    u, d, ex, ne = L
    d = set(d)
    return ex in d


def inSetMethod_UniqueValue_ValueNotExisting(L):
    u, d, ex, ne = L
    u = set(u)
    return ne in u


def inSetMethod_DuplicateValue_ValueNotExisting(L):
    u, d, ex, ne = L
    d = set(d)
    return ne in d


perfplot.show(
    setup=setupTest,
    equality_check=None,
    kernels=[
        inListMethod_UniqueValue_ValueExisting,
        inListMethod_DuplicateValue_ValueExisting,
        inListMethod_UniqueValue_ValueNotExisting,
        inListMethod_DuplicateValue_ValueNotExisting,
        inSetMethod_UniqueValue_ValueExisting,
        inSetMethod_DuplicateValue_ValueExisting,
        inSetMethod_UniqueValue_ValueNotExisting,
        inSetMethod_DuplicateValue_ValueNotExisting,
    ],
    labels=[
        "inListMethod_UniqueValue_ValueExisting",
        "inListMethod_DuplicateValue_ValueExisting",
        "inListMethod_UniqueValue_ValueNotExisting",
        "inListMethod_DuplicateValue_ValueNotExisting",
        "inSetMethod_UniqueValue_ValueExisting",
        "inSetMethod_DuplicateValue_ValueExisting",
        "inSetMethod_UniqueValue_ValueNotExisting",
        "inSetMethod_DuplicateValue_ValueNotExisting",
    ],
    n_range=[2 ** k for k in range(2, 20)],
    xlabel="Data Length",
    logx=True,
    logy=True,
)