Programming

파이썬 :리스트에서 요소 찾기

procodes 2020. 6. 8. 21:56
반응형

파이썬 :리스트에서 요소 찾기


이 질문에는 이미 답변이 있습니다.

파이썬에서 목록에서 요소의 색인을 찾는 좋은 방법은 무엇입니까?

 

목록이 정렬되지 않았을 수 있습니다.사용할 비교 연산자를 지정하는 방법이 있습니까?


가장 좋은 방법은 아마도

list 메소드 .index

를 사용하는 것입니다 .목록에있는 객체의 경우 다음과 같은 작업을 수행 할 수 있습니다.

def __eq__(self, other):
    return self.Value == other.Value

특별한 처리가 필요합니다.enumerate (arr)와 함께 for / in 문을 사용할 수도 있습니다값이 100보다 큰 항목의 색인을 찾는 예입니다.

for index, item in enumerate(arr):
    if item > 100:
        return index, item

출처


에서

다이빙 속으로 파이썬

:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

요소가 목록에 포함되어 있는지 확인하려면 다음을 수행하십시오.

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

다음은 목록 이해를 사용하는 또 다른 방법입니다 (일부 사람들은 논란의 여지가 있습니다). 간단한 테스트, 예를 들어 객체 속성에 대한 비교 (많이 필요함)에 매우 접근하기 쉽습니다.

el = [x for x in mylist if x.attr == "foo"][0]

물론 이것은 목록에 적합한 요소가 존재한다고 가정합니다 (실제로는 고유성).


numpy 배열에서 값을 찾으려고 가정하면 다음과 같이 작동 할 수 있습니다.

Numpy.where(arr=="value")[0]

거기입니다

index

방법은

i = array.index(value)

,하지만 난 당신이 사용자 정의 비교 연산자를 지정할 수 있다고 생각하지 않습니다. 그래도 자신 만의 함수를 작성하는 것은 어렵지 않습니다.

def custom_index(array, compare_function):
    for i, v in enumerate(array):
        if compare_function(v):
            return i

목록의 색인 메소드가이를 수행합니다. 순서를 보장하려면을 사용하여 목록을 먼저 정렬하십시오

sorted()

. 정렬은 정렬 방법을 지시하기 위해 cmp 또는 키 매개 변수를 승인합니다.

a = [5, 4, 3]
print sorted(a).index(5)

또는:

a = ['one', 'aardvark', 'a']
print sorted(a, key=len).index('a')

일치하는 요소 (Python 2.6)의 색인을 반환하는 함수를 사용합니다.

def index(l, f):
     return next((i for i in xrange(len(l)) if f(l[i])), None)

그런 다음 람다 함수를 통해이를 사용하여 필요한 방정식 (예 : 요소 이름 사용)으로 필요한 요소를 검색하십시오.

element = mylist[index(mylist, lambda item: item["name"] == "my name")]

내 코드의 여러 곳에서 사용해야하는 경우 특정 찾기 기능을 정의합니다 (예 : 이름으로 요소 찾기).

def find_name(l, name):
     return l[index(l, lambda item: item["name"] == name)]

그리고 그것은 매우 쉽고 읽기 쉽습니다.

element = find_name(mylist,"my name")

나는 일부 토토를 조정하여 이것을 발견했다. 구글과 당신에게 감사합니다;)

def findall(L, test):
    i=0
    indices = []
    while(True):
        try:
            # next value in list passing the test
            nextvalue = filter(test, L[i:])[0]

            # add index of this value in the index list,
            # by searching the value in L[i:] 
            indices.append(L.index(nextvalue, i))

            # iterate i, that is the next index from where to search
            i=indices[-1]+1
        #when there is no further "good value", filter returns [],
        # hence there is an out of range exeption
        except IndexError:
            return indices

매우 간단한 사용법 :

a = [0,0,2,1]
ind = findall(a, lambda x:x>0))

[2, 3]

PS scuse 내 영어


이건 어때?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

용법:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

참고 URL :

https://stackoverflow.com/questions/604802/python-finding-an-element-in-a-list

반응형