티스토리 뷰

반응형

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

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

 

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

How to sort a list/tuple of lists/tuples by the element at a given index?

특정 인덱스의 요소를 기준으로 리스트/튜플을 정렬하는 방법은?

 문제 내용 

I have some data either in a list of lists or a list of tuples, like this:

다음과 같이 리스트의 리스트 또는 튜플의 리스트를 데이터로 가지고 있습니다:
data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]

 

And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list?

그리고 저는 하위 집합에서 2번째 요소를 기준으로 정렬하고 싶습니다. 즉, (1, 2, 3)에서 2, (4, 5, 6)에서 5, (7, 8, 9)에서 8을 기준으로 정렬하고 싶습니다. 이를 위해 어떤 일반적인 방법이 있을까요? 제 리스트에는 튜플이나 리스트를 저장해야 할까요?

 

 

 

 높은 점수를 받은 Solution 

sorted_by_second = sorted(data, key=lambda tup: tup[1])

 

or:

또는:
data.sort(key=lambda tup: tup[1])  # sorts in place

 

The default sort mode is ascending. To sort in descending order use the option reverse=True:

기본 정렬 모드는 오름차순입니다. 내림차순으로 정렬하려면 옵션으로 reverse=True를 사용하면 됩니다.
sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)

 

or:

또는:
data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place

 

 

 가장 최근 달린 Solution 

@Stephen 's answer is to the point! Here is an example for better visualization,

@Stephen의 답변이 가장 적합합니다! 더 잘 이해하기 위해 아래 예제를 살펴보세요.

 

Shout out for the Ready Player One fans! =)

레디 플레이어 원 팬 여러분, 소리 질러주세요! =)
>>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')]
>>> gunters.sort(key=lambda tup: tup[0])
>>> print gunters
[('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]

key is a function that will be called to transform the collection's items for comparison.. like compareTo method in Java.

키는 비교를 위해 컬렉션 항목을 변환하기 위해 호출되는 함수입니다. 자바에서의 compareTo 메서드와 유사합니다.

 

The parameter passed to key must be something that is callable. Here, the use of lambda creates an anonymous function (which is a callable).
The syntax of lambda is the word lambda followed by a iterable name then a single block of code.

key에 전달된 매개변수는 호출 가능한 것이어야 합니다. 여기서 lambda의 사용으로 익명 함수(호출 가능한)를 생성합니다. lambda의 구문은 단일 코드 블록 뒤에 따라오는 반복 가능한 이름이라는 단어로 구성됩니다.

 

Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.

아래 예제에서는 특정 이벤트와 배우 이름에 대한 정보를 보유한 튜플의 리스트를 정렬합니다.

 

We are sorting this list by time of event occurrence - which is the 0th element of a tuple.

여기서 우리는 이벤트 발생 시간 - 즉, 튜플의 0번째 요소를 기준으로 이 리스트를 정렬합니다.

 

Note - s.sort([cmp[, key[, reverse]]]) sorts the items of s in place

참고 - s.sort([cmp[, key[, reverse]]])는 s의 항목을 제자리에서 정렬합니다.

 

 

 

출처 : https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index

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