반응형
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
반응형
'Program Tip' 카테고리의 다른 글
WPF에서 Xaml 파일에 주석을 추가하는 방법은 무엇입니까? (0) | 2020.10.26 |
---|---|
접두사를 포함하는 knockoutjs로 id 속성 설정 (0) | 2020.10.26 |
ID 목록에서 Entity Framework의 여러 행 업데이트 (0) | 2020.10.26 |
Lollipop 도구 모음 애니메이션 펼치기 / 접기 (텔레 그램 앱) (0) | 2020.10.26 |
APL 대 A 대 J 대 K? (0) | 2020.10.26 |