티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Sorting list according to corresponding values from a parallel list
병렬 리스트에서 해당 값에 따라 리스트 정렬하기
문제 내용
I have a list of strings like this:
저는 다음과 같은 문자열 리스트가 있습니다:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
What is the shortest way of sorting X using values from Y to get the following output?
Y의 값을 사용하여 X를 정렬하는 가장 짧은 방법은 무엇인가요? 아래와 같은 출력을 얻을 수 있도록 해야합니다.
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
The order of the elements having the same "key" does not matter. I can resort to the use of for
constructs but I am curious if there is a shorter way. Any suggestions?
"key"가 같은 요소들의 순서는 중요하지 않습니다. for문을 사용하는 것도 가능하지만 더 간단한 방법이 있는지 궁금합니다. 어떤 제안이 있으신가요?
높은 점수를 받은 Solution
Shortest Code
"Shortest Code"는 코드를 최대한 짧게 작성하는 것을 의미합니다.
[x for _, x in sorted(zip(Y, X))]
Example:
예시:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Z = [x for _,x in sorted(zip(Y,X))]
print(Z) # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Generally Speaking
일반적으로 말하면..
[x for _, x in sorted(zip(Y, X), key=lambda pair: pair[0])]
Explained:
설명:
zip
the twolist
s.- create a new, sorted
list
based on thezip
usingsorted()
. - using a list comprehension extract the first elements of each pair from the sorted, zipped
list
.
1. 두 리스트를 zip 해서 묶습니다.
2. sorted()를 사용해 zip을 기반으로 한 새로운 정렬된 리스트를 생성합니다.
3. 리스트 내포를 사용해서 정렬된 zip 리스트에서 각 쌍의 첫 번째 요소를 추출합니다.
For more information on how to set\use the key
parameter as well as the sorted
function in general, take a look at this.
key 매개변수를 설정하거나 sorted 함수를 일반적으로 사용하는 방법에 대한 자세한 정보는 이 링크를 참조해주세요.
가장 최근 달린 Solution
This is an old question but some of the answers I see posted don't actually work because zip
is not scriptable. Other answers didn't bother to import operator
and provide more info about this module and its benefits here.
이 질문은 오래된 질문이지만, 일부 게시된 답변들은 zip이 scriptable하지 않기 때문에 실제로 작동하지 않습니다. 다른 답변들은 operator를 import하지 않았으며 이 모듈과 그 혜택에 대해 더 많은 정보를 제공하지 않았습니다.
There are at least two good idioms for this problem. Starting with the example input you provided:
이 문제에 대한 좋은 방법이 적어도 두 가지 이상 있습니다. 제공된 입력 예시부터 시작해봅시다.
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
Using the "Decorate-Sort-Undecorate" idiom
"Decorate-Sort-Undecorate" 관용구 사용
This is also known as the Schwartzian_transform after R. Schwartz who popularized this pattern in Perl in the 90s:
이것은 90년대에 Perl에서 이 패턴을 대중화시킨 R. Schwartz의 이름을 딴 Schwartzian_transform으로도 알려져 있습니다.
# Zip (decorate), sort and unzip (undecorate).
# Converting to list to script the output and extract X
list(zip(*(sorted(zip(Y,X)))))[1]
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
Note that in this case Y
and X
are sorted and compared lexicographically. That is, the first items (from Y
) are compared; and if they are the same then the second items (from X
) are compared, and so on. This can create unstable outputs unless you include the original list indices for the lexicographic ordering to keep duplicates in their original order.
참고로 이 경우에는 Y와 X가 정렬되어 사전식으로 비교됩니다. 즉, 첫 번째 항목(Y의 항목)이 비교되고, 그것이 같으면 두 번째 항목(X의 항목)이 비교되며, 이와 같은 방식으로 비교됩니다. 이렇게하면 중복 항목을 원래 순서대로 유지하기 위해 사전식 순서에 원래 목록 인덱스를 포함해야 하므로 불안정한 출력이 발생할 수 있습니다.
Using the operator
module
연산자 모듈 사용
This gives you more direct control over how to sort the input, so you can get sorting stability by simply stating the specific key to sort by. See more examples here.
이 방법은 입력을 어떻게 정렬할지에 대한 직접적인 제어를 제공하여 정렬 안정성을 특정 정렬 기준을 명시하는 것으로 얻을 수 있습니다. 더 많은 예제는 여기에서 확인할 수 있습니다.
import operator
# Sort by Y (1) and extract X [0]
list(zip(*sorted(zip(X,Y), key=operator.itemgetter(1))))[0]
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
출처 : https://stackoverflow.com/questions/6618515/sorting-list-according-to-corresponding-values-from-a-parallel-list
'개발 > 파이썬' 카테고리의 다른 글
딕셔너리에서 첫 번째 키를 찾는 방법 (0) | 2023.02.05 |
---|---|
리스트 zip을 반대로 수행하기(튜플 리스트를 두개의 리스트로 변환하기) (0) | 2023.02.04 |
점 "."을 사용하여 딕셔너리 멤버에 접근하기 (0) | 2023.02.04 |
딕셔너리에서 키-값 쌍의 하위 집합 만들기 (0) | 2023.02.04 |
CSV 파일 한 줄씩 작성하기 (0) | 2023.02.03 |