문제

Python의 목록 유형에는 하나의 매개 변수를 가져와 매개 변수와 일치하는 목록에서 첫 번째 항목의 인덱스를 반환하는 index () 메소드가 있습니다. 예를 들어:

>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3

이것을 튜플과 같은 복잡한 물체의 목록으로 확장하는 우아한 (관용적) 방법이 있습니까? 이상적으로는 다음과 같은 일을 할 수 있기를 원합니다.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2

getIndexOftuple ()는 하위 인덱스와 값을 수용 한 다음 해당 하위 인덱스에서 주어진 값으로 목록 항목의 색인을 반환하는 가상의 방법 일뿐입니다. 나는 희망

목록 이해력이나 람바 등을 사용하여 그 일반적인 결과를 달성 할 수있는 방법이 있습니까? 나는 내 자신의 수업과 방법을 쓸 수 있다고 생각하지만 Python이 이미 할 수있는 방법이 있다면 바퀴를 재발 명하고 싶지 않습니다.

도움이 되었습니까?

해결책

이건 어때?

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]

주석에서 지적한 바와 같이, 이것은 모든 경기가 발생합니다. 첫 번째를 얻으려면 다음을 수행 할 수 있습니다.

>>> [y[0] for y in tuple_list].index('kumquat')
2

게시 된 모든 솔루션 간의 속도 차이에 대한 의견에는 좋은 논의가 있습니다. 나는 약간 편견이 있을지 모르지만 우리가 말하는 속도 가이 문제에 대한 기능을 만들고 모듈을 가져 오는 것과 비교하여 개인적으로 한 라이너를 고수 할 것입니다. 그러나이 문제를 매우 많은 양으로 계획하고 있다면 내가 제공 한 것보다 빠르기 때문에 제공된 다른 답변을보고 싶을 수도 있습니다.

다른 팁

그 목록 이해는 잠시 후에 지저분합니다.

나는이 Pythonic 접근법을 좋아합니다.

from operator import itemgetter

def collect(l, index):
   return map(itemgetter(index), l)

# And now you can write this:
collect(tuple_list,0).index("cherry")   # = 1
collect(tuple_list,1).index("3")        # = 2

코드가 모두 슈퍼 성능이 필요한 경우 :

# Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
    for pos,t in enumerate(l):
        if t[index] == value:
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry")   # = 1

한 가지 가능성은 다음을 사용하는 것입니다 ItemGetter 기능 operator 기준 치수:

import operator

f = operator.itemgetter(0)
print map(f, tuple_list).index("cherry") # yields 1

전화 itemgetter 동등한 기능을 반환합니다 foo[0] 그것에 전달 된 모든 것을 위해. 사용 map, 그런 다음 해당 기능을 각 튜플에 적용하여 정보를 새 목록으로 추출한 다음 index 정상적으로.

map(f, tuple_list)

다음과 같습니다.

[f(tuple_list[0]), f(tuple_list[1]), ...etc]

차례로 다음과 같습니다.

[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]

주는 것 :

["pineapple", "cherry", ...etc]

목록 이해력 및 색인 () 로이 작업을 수행 할 수 있습니다.

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1

나는 이것을 Tripttych에 대한 의견으로 배치 할 것이지만, 등급 부족으로 아직 언급 할 수 없습니다.

열거 자 메소드를 사용하여 튜플 목록에서 하위 색인과 일치합니다. 예를 들어

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
        ('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

    # if index is a tuple of subindices to match against:
    for pos,k in enumerate(li):
        match = True
        for i in indices:
            if k[i] != vals[i]:
                match = False
                break;
        if (match):
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals)    # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 4

에서 영감을 받다 이 질문, 나는 이것이 매우 우아하다고 생각했다 :

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> next(i for i, t in enumerate(tuple_list) if t[1] == 7)
1
>>> next(i for i, t in enumerate(tuple_list) if t[0] == "kumquat")
2

좋아, 실수일지도 모른다 vals(j), 보정은 다음과 같습니다.

def getIndex(li,indices,vals):
for pos,k in enumerate(lista):
    match = True
    for i in indices:
        if k[i] != vals[indices.index(i)]:
            match = False
            break
    if(match):
        return pos
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

def eachtuple(tupple, pos1, val):
    for e in tupple:
        if e == val:
            return True

for e in tuple_list:
    if eachtuple(e, 1, 7) is True:
        print tuple_list.index(e)

for e in tuple_list:
    if eachtuple(e, 0, "kumquat") is True:
        print tuple_list.index(e)
z = list(zip(*tuple_list))
z[1][z[0].index('persimon')]

몸이 람다를 제안하지 않습니까?

y 이것을 시도하고 작동합니다. 나는이 게시물 검색 답변에옵니다. 나는 내가 좋아한다는 것을 찾지 못했지만, 나는 욕심을 느낀다 : P

    l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]]

    map(lambda x:x[0], l).index("pato") #1 

예제를 추가하려면 편집 :

   l=[['rana', 1, 1], ['pato', 2, 1], ['perro', 1, 1], ['pato', 2, 2], ['pato', 2, 2]]

조건별로 모든 항목을 추출합니다 : 필터 (Lambda x : x [0] == "pato", l) #[[ 'pato', 2, 1], [ 'pato', 2, 2], [ 'pato', 2, 2]

색인으로 조건으로 모든 항목을 추출합니다.

    >>> filter(lambda x:x[1][0]=="pato", enumerate(l))
    [(1, ['pato', 2, 1]), (3, ['pato', 2, 2]), (4, ['pato', 2, 2])]
    >>> map(lambda x:x[1],_)
    [['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]

참고 : _ 변수는 대화식 통역사에서만 작동합니다 y 일반 텍스트 파일 _ Need Quessivicti 할당, IE _ = 필터 (Lambda x : X [1] [0] == "Pato", enumerate (l))

Python의 List.Index (x)는 목록에서 X의 첫 번째 발생에 대한 인덱스를 반환합니다. 따라서 목록 압축으로 반환 된 개체를 통과하여 색인을 얻을 수 있습니다.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']
[2]

같은 줄을 사용하면 여러 개의 일치 요소가있는 경우 인덱스 목록을 얻을 수도 있습니다.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

다음은 가장 좋은 방법이 아니라고 생각합니다 (속도와 우아함 문제). 도움이 될 수 있습니다.

from collections import OrderedDict as od
t = [('pineapple', 5), ('cherry', 7), ('kumquat', 3), ('plum', 11)]
list(od(t).keys()).index('kumquat')
2
list(od(t).values()).index(7)
7
# bonus :
od(t)['kumquat']
3

2 명의 멤버가있는 튜플 목록은 주문한 dict로 직접 변환 할 수 있으며, 데이터 구조는 실제로 동일하므로 Dict Method를 즉시 사용할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top