Program Tip

Python의 튜플 목록에서 최대 값 찾기

programtip 2020. 10. 26. 08:32
반응형

Python의 튜플 목록에서 최대 값 찾기


중복 가능성 :
중첩 된 목록의 두 번째 요소를 기준으로 최대 값 정렬 또는 찾기. 파이썬

다음과 같이 ~ 10 ^ 6 튜플이있는 목록이 있습니다.

[(101, 153), (255, 827), (361, 961), ...]
  ^     ^
  X     Y

이 목록에서 Y의 최대 값을 찾고 싶지만 바인딩 된 X도 알고 싶습니다.

어떻게해야합니까?


사용 max():

 
사용 itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

사용 lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit 비교:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

max 외에도 다음을 정렬 할 수 있습니다.

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

목록을 반복하고 튜플을 변수에 유지하면 동일한 변수에서 두 값을 모두 볼 수 있습니다.

num=(0, 0)
for item in tuplelist:
  if item[1]>num[1]:
    num=item #num has the whole tuple with the highest y value and its x value

참고 URL : https://stackoverflow.com/questions/13145368/find-the-maximum-value-in-a-list-of-tuples-in-python

반응형