5.1.4. Nested List Comprehensions
중첩된 List Comprehension
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
List Comprehension의 첫 표현식은 그 안에 또다른 List Comprehension을 포함할 수 있습니다.
Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:
3x4 행렬(=matrix)이 각각 4개의 항목을 가진 3개의 리스트로 만들어 진 것을 살펴봅시다.
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
The following list comprehension will transpose rows and columns:
List Comprehension을 통해 열과 행을 바꿔 보겠습니다.
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
As we saw in the previous section, the nested listcomp is evaluated in the context of the for
that follows it, so this example is equivalent to:
우리가 앞서 살펴본 바와 같이, 중첩된 List Comprehension은 그 안의 for문을 맥락에 따라 실행합니다. 따라서 이 예는 아래의 예와 같은 결과를 가집니다.
>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
which, in turn, is the same as:
같은 결과를 내는 또다른 예시 입니다.
>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:
사실 내장함수를 쓰는 쪽이 더 편리할 수도 있습니다. zip()
내장함수가 이런 경우 유용합니다.
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
See Unpacking Argument Lists for details on the asterisk in this line.
matrix앞에 붙은 별표(=asterisk)에 대하여는Unpacking Argument Lists 를 참고하십시오.
(4.7.4. Unpacking Argument Lists)