codememo

튜플 목록에서 요소 찾기

tipmemo 2023. 5. 8. 22:15
반응형

튜플 목록에서 요소 찾기

목록 'a'가 있습니다.

a= [(1,2),(1,4),(3,5),(5,7)]

특정 번호의 튜플을 모두 찾아야 합니다.1의 경우는 될 것이라고 말합니다.

result = [(1,2),(1,4)]

그걸 어떻게 하는 거죠?

첫 번째 숫자만 일치시키려면 다음과 같이 수행할 수 있습니다.

[item for item in a if item[0] == 1]

1개가 들어 있는 튜플만 검색하는 경우:

[item for item in a if 1 in item]

실제로 각 튜플의 크기가 2인 튜플 목록에 유용한 영리한 방법이 있습니다. 목록을 하나의 사전으로 변환할 수 있습니다.

예를들면,

test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1

목록 이해도에 대한 읽기

[ (x,y) for x, y in a if x  == 1 ]

또한 제너레이터 기능 및yield진술.

def filter_value( someList, value ):
    for x, y in someList:
        if x == value :
            yield x,y

result= list( filter_value( a, 1 ) )
[tup for tup in a if tup[0] == 1]
for item in a:
   if 1 in item:
       print item

filter기능은 또한 흥미로운 해결책을 제공할 수 있습니다.

result = list(filter(lambda x: x.count(1) > 0, a))

리스트에서 튜플을 검색하는 것.a어떤 경우에도1검색이 첫 번째 요소로 제한되는 경우 솔루션을 다음으로 수정할 수 있습니다.

result = list(filter(lambda x: x[0] == 1, a))

또는takewhile(이 외에도 더 많은 값의 예가 나와 있습니다):

>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 

정렬되지 않은 경우, 예:

>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 

필터 기능 사용:

>> defet_values(반복 가능, 키_to_find):
반환 목록(필터 x:key_to_find in x, 반복 가능) >>a = [(1,2),(1,4),(3,5),(5,7)] >> get_values(a, 1) >>> [(1, 2), (1, 4)]
>>> [i for i in a if 1 in i]

[(1, 2), (1, 4)]

튜플에 있는 숫자를 검색하려면 다음을 사용할 수 있습니다.

a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)

print(result)

사용할 수도 있습니다.if i==j[0] or i==j[index]특정 인덱스에서 숫자를 검색하려면

언급URL : https://stackoverflow.com/questions/2191699/find-an-element-in-a-list-of-tuples

반응형