티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Sort a list of tuples by 2nd item (integer value)

두 번째 아이템(정수 값)으로 튜플 리스트 정렬하기

 문제 내용 

I have a list of tuples that looks something like this:

다음과 같은 튜플 리스트가 있습니다.
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

 

I want to sort this list in ascending order by the integer value inside the tuples. Is it possible?

이 리스트를 튜플 내부의 정수 값을 기준으로 오름차순으로 정렬하려면 어떻게 해야 할까요?

 

 

 

 높은 점수를 받은 Solution 

Try using the key keyword with sorted().

sorted() 함수와 key 키워드를 사용하세요.
sorted(
    [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], 
    key=lambda x: x[1]
)

 

key should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1].

key는 데이터 구조에서 비교 가능한 요소를 검색하는 방법을 식별하는 함수여야 합니다. 이 경우 튜플의 두 번째 요소이므로 [1]에 접근합니다.

 

For optimization, see jamylak's response using itemgetter(1), which is essentially a faster version of lambda x: x[1].

성능을 위해 jamylak의 itemgetter(1)을 사용하는 것도 고려해보세요. 이는 사실상 lambda x: x[1]의 빠른 버전입니다.

 

 

 

 가장 최근 달린 Solution 

For an in-place sort, use

제자리 정렬을 위해 다음을 사용하세요.
foo = [(list of tuples)]
foo.sort(key=lambda x:x[0]) #To sort by first element of the tuple

 

 

출처 : https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value

반응형
댓글
공지사항
최근에 올라온 글