source

Python: 목록에서 찾기

nicesource 2022. 11. 5. 17:24
반응형

Python: 목록에서 찾기

는 다음 을 참고하여 '있다'는 것을 확인합니다.itemmy_list:

if item in my_list:
    print("Desired item is in list")

하지만 때때로, 그것은 그 물건을 찾지 못한다.왜 이러한가?


아, 아, 아, .if item in my_list:목록에서 항목을 찾는 가장 "비음파적인" 방법?

번째 질문입니다 "그러다"if item is in my_list: "좋다"면 .item내부 요소 중 하나와 동일합니다.my_list. 항목은 목록 항목과 정확히 일치해야 합니다.예를 들어."abc" ★★★★★★★★★★★★★★★★★」"ABC"일치하지 않습니다.특히 부동 소수점 값은 부정확할 수 있습니다.를 들면, 「 」입니다.1 - 1/3 != 2/3.

두 번째 질문입니다.리스트에서 「찾기」를 하면, 실제로 몇개의 방법이 있습니다.

내용물 확인

하다록록 、 무엇무무무것 인인것것 。'하다'를 사용할 수 .in★★★★★★★★★★★★★★★★★★:

3 in [1, 2, 3] # => True

컬렉션 필터링

즉, 특정 조건을 충족하는 시퀀스의 모든 요소를 찾는 것입니다.여기에는 목록 이해 또는 생성기 식을 사용할 수 있습니다.

matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

후자는 생성기를 반환합니다. 생성기는 반복할 때에만 작성되는 게으른 목록으로 생각할 수 있습니다.그런데 첫 번째 것은 정확히 같은 것입니다.

matches = filter(fulfills_some_condition, lst)

Python 2에 있습니다.여기서 작업 중인 고차 함수를 볼 수 있습니다.3, Python 3의 경우filter목록을 반환하지 않고 생성기 같은 개체를 반환합니다.

첫 번째 오카렌스 찾기

하는 첫 번째 만을 원하는 ), for loop)을 else을 참조해 주세요. 이 때 하실 수 있습니다.

next(x for x in lst if ...)

되거나 첫 번째 일치가 됩니다.StopIteration찾을 수 없는 경우.'보다 낫다'를 .

next((x for x in lst if ...), [default value])

항목의 위치 찾기

'우리'라는 것도 index이 메서드는 목록 내의 특정 요소가 어디에 있는지 알고 싶을 때 도움이 될 수 있습니다.

[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError

이 있는 는, 「」, 「」가 되는 해 주세요..index는 항상 를 반환합니다가장 낮은 인덱스는 다음과 같이 입력합니다.

[1,2,3,2].index(2) # => 1

된 인덱스가 모든 인덱스가 " " "를할 수 있습니다.enumerate()★★★★

[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]

또는1개의 요소를 Nonenext 안 된다StopIteration"CHANGE: "CHANGE: "CHANGE: " 。

first_or_default = next((x for x in lst if ...), None)

Niklas B.의 답변은 매우 포괄적이지만 목록에서 항목을 찾고 싶을 때 인덱스를 얻는 것이 유용할 수 있습니다.

next((i for i, x in enumerate(lst) if [condition on x]), [default value])

첫 번째 오카렌스 찾기

교육기관에는 이에 대한 레시피가 있습니다.

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

예를 들어, 다음 코드는 목록의 첫 번째 홀수를 찾습니다.

>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3  

복사/붙여넣기 또는 설치 가능

pip3 install more-itertools

이 레시피는 이미 포함되어 있습니다.

다른으로는 '있다'가 있는 할 수 .if item in list:단, 주문 O(n)입니다.항목의 큰 목록을 다루고 있으며 목록 구성원인지 여부만 알면 되는 경우 먼저 목록을 세트로 변환하고 일정한 시간 집합 검색을 이용할 수 있습니다.

my_set = set(my_list)
if item in my_set:  # much faster on average than using a list
    # do something

모든 경우에 올바른 솔루션은 아니지만 경우에 따라서는 이 솔루션이 더 나은 성능을 제공할 수 있습니다.

「 」로 에 주의해 .set(my_list)또한 O(n)이기 때문에 이 작업을 한 번만 수행할 필요가 있다면 이 방법으로 수행하는 것이 빠르지 않습니다.멤버십을 반복적으로 확인해야 하는 경우 초기 세트 작성 후 모든 룩업에 대해 O(1)가 됩니다.

정의와 사용방법

count()방법

구문

list.count(value)

예:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

질문의 예:

item = someSortOfSelection()

if myList.count(item) >= 1 :

    doMySpecialFunction(item)

문자열 목록을 사용할 때 다음 두 가지 검색 중 하나를 사용할 수 있습니다.

  1. 목록 요소가 항목과 동일한 경우('list'는 ['one', 'two'에 있음):

    if item in your_list: some_function_on_true()

    ['one', 'ex', 'two'의 'ex'] => True

    ['one' 'ex' 'two']의 'ex_1' => False

  2. 목록 요소가 항목과 같은 경우('ex'는 [1', '2'에 있음) 또는 '1'은 [1', '2'에 있음):

    matches = [el for el in your_list if item in el]

    또는

    matches = [el for el in your_list if el in item]

    그냥 해 주세요.len(matches)또는 필요에 따라 읽습니다.

「 」를 하는 대신에, 「 」를 사용합니다.list.index(x) x 하거나 "x" x "x" 를 합니다.#ValueError 수 x를 사용할 수 .list.count(x)목록에 x가 실제로 있는지 확인) 또는 목록에 0이 반환됩니다(x가 없는 경우).★★★★★의 멋진 점count(), x가 에 대해 를 둘 것입니다.

수집에 값이 존재하는지 한 번 확인하려는 경우 'in' 연산자를 사용하면 됩니다.단, 여러 번 체크할 예정이라면 이등분 모듈을 사용하는 것을 추천합니다.이등분할모듈데이터는정렬해야 합니다.데이터를 한 번 정렬한 다음 이등분할을 사용할 수 있습니다.내 기계에서 이등분 모듈을 사용하는 것이 'in' 연산자를 사용하는 것보다 약 12배 빠릅니다.

다음은 Python 3.8 이상의 구문을 사용하는 코드의 예입니다.

import bisect
from timeit import timeit

def bisect_search(container, value):
    return (
      (index := bisect.bisect_left(container, value)) < len(container) 
      and container[index] == value
    )

data = list(range(1000))
# value to search
true_value = 666
false_value = 66666

# times to test
ttt = 1000

print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")

t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)

print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")

출력:

bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71

내가 몇 번 시험했을 때 아마 화이트 스페이스와 라인 피드가 간섭을 해서 이 해결책을 제시하게 된 것 같다고 말씀하셨죠.

myList=[" test","ok","ok1"]
item = "test"#someSortOfSelection()
if  True in list(map(lambda el : item in el ,myList)):
    doMySpecialFunction(item)

루프

def for_loop(l, target):
    for i in l:
        if i == target:
            return i
    return None


l = [1, 2, 3, 4, 5]
print(for_loop(l, 0))
print(for_loop(l, 1))
# None
# 1

다음 분.

def _next(l, target):
    return next((i for i in l if i == target), None)


l = [1, 2, 3, 4, 5]
print(_next(l, 0))
print(_next(l, 1))
# None
# 1

more_itertools

more_itertools.first_true(iterable, default=None, pred=None)

설치하다

pip install more-itertools

또는 직접 사용

def first_true(iterable, default=None, pred=None):
    return next(filter(pred, iterable), default)
from more_itertools import first_true

l = [1, 2, 3, 4, 5]
print(first_true(l, pred=lambda x: x == 0))
print(first_true(l, pred=lambda x: x == 1))
# None
# 1

비교하다

방법 시간/초
루프 2.77
다음() 3.64
more_itertools.first_true() 3.82 또는 10.86
import timeit
import more_itertools


def for_loop():
    for i in range(10000000):
        if i == 9999999:
            return i
    return None


def _next():
    return next((i for i in range(10000000) if i == 9999999), None)


def first_true():
    return more_itertools.first_true(range(10000000), pred=lambda x: x == 9999999)


def first_true_2():
    return more_itertools.first_true((i for i in range(10000000) if i == 9999999))


print(timeit.timeit(for_loop, number=10))
print(timeit.timeit(_next, number=10))
print(timeit.timeit(first_true, number=10))
print(timeit.timeit(first_true_2, number=10))
# 2.7730861
# 3.6409407000000003
# 10.869996399999998
# 3.8214487000000013

문자열 목록 항목에 추가/불필요한 공백이 없는지 확인합니다.그렇기 때문에 상품을 찾을 수 없는 이유를 설명할 수 있습니다.

 lstr=[1, 2, 3]
 lstr=map(str,lstr)
 r=re.compile('^(3){1}')
 results=list(filter(r.match,lstr))
 print(results)

in와 함께 동작합니다.list()dict() too: s 도도 s s s s s s s 。

a = [ {"a":1}, {"b":1, "c":1} ]

b = {"c":1 , "b":1} # <-- No matter the order
    
if b in a: 
    print("b is in a")

적어도 Python 3.8.10에서는 순서와 관계없이

언급URL : https://stackoverflow.com/questions/9542738/python-find-in-list

반응형