5.1.3. List Comprehension

리스트 이해식


참고
List Comprehension을 번역할 적당한 단어가 떠오르지 않아 원어 그대로 사용합니다.


List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
List comprehension은 리스트를 간결한 방법으로 만들어낼 수 있습니다. 일반적인 방식은 새로운 리스트를 만들기 위해 각각의 요소에 대해 알아야 합니다. 그것들이 어떤 시퀀스 또는 iterable의 각 구성요소에 적용된 명령의 결과인지 말입니다. 또는 특정 조건을 만족하는 요소들로 하위순서를 만들어야 합니다.

For example, assume we want to create a list of squares, like:
예를 들어, 우리가 제곱수의 리스트를 만들기 위해서는 다음과 같은 과정을 거치게 됩니다.

>>> squares = [ ]
>>> for x in range(10):
...    squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:
이러한 방식은 loop가 끝난 후에도 남아있는 x라는 이름의 변수를 만든다는 것을 (또는 덮어쓴다는 것을) 주의하십시오. 우리는 제곱수의 리스트를 이러한 부작용 없이도 만들 수 있습니다. 다음과 같이 말입니다.

squares = list(map(lambda x: x**2, range(10)))

or, equivalently:
또는 이렇게도 할 수 있습니다.

sqaures = [x**2 for x in range(10)]

which is more concise and readable. 아래의 두 방식이 보다 간결하고 읽기에도 편합니다.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:
하나의 List Comprehension은 표현식을 포함하는 대괄호로 이루어집니다. 대괄호 안의 표현식에는 for문 또는 if절이 들어있습니다. for문이나 if절의 맥락을 따라 표현식을 계산하면 List Comprehension의 답이 나오고, 그 답은 새로운 리스트가 됩니다. 예를 들어, 다음 List Comprehension은 두 개 리스트의 구성요소들을 합칠 수 있습니다. 그 리스트들이 서로 다를지라도 말입니다.

>>> [(x,y) for x in [1,2,3] for y in [3,1,4] if x !=y ]
[(1,3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it's equivalent to :
이것은 다음 예시와 동일합니다.

>>> combs = []  # combs: combines, 빈 리스트를 미리 만들어 둔다.
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the for and if statements is the same in both these snippets.
for문과 if문이 List Comprehension에서 얼마나 간결하게 사용되었는지 보십시오.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.
만약 표현식이 튜플(예: (x,y))이었다면 괄호로 둘러싸 주면 됩니다.

>>> vec = [-4, -2, 0, 2, 4]
    # 각 항목이 2배가 되는 새로운 리스트를 만들어 보자.
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]

    # 새로운 리스트에서 음수를 걸러내보자.
>>> [x for x in vec if x >= 0]
[0, 2, 4]

    # 모든 항목에 함수를 적용해 보자. 
    # abs()는 각 항목의 절대값을 반환하는 함수다. abs = absolute 
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]

    # 각 항목에 메소드를 호출해보자.
    # .strip()은 공백을 지우는 메소드이다.
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']

    # (number, square)로 구성된 튜플과, 그 튜플로 구성된 리스트를 만들어 보자.
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

    # 튜플은 반드시 괄호로 둘러싸여야 한다. 그렇지 않은 경우 오류메시지가 나타난다. 
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in ?
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax  # 오류메시지


    # 두 개의 for을 사용하여 하위 리스트들을 하나의 리스트로 만들어보자.
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

참고) vec 는 vector (= 크기와 방향으로 정해지는 양)을 의미하는 듯 하다.

참고이미지)

List comprehensions can contain complex expressions and nested functions:
List Comprehension은 다중 표현식과 중첩된 함수를 포함할 수 있습니다.

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

results matching ""

    No results matching ""