3-1-3-31. List Comprehensions

we created a list of capitalized cities from the cities list in a for loop.

With a list comprehension,

we can get the same result like this.

List comprehensions allow us to create a list using a for loop in one step.

You create a list comprehension with brackets including

an expression to evaluate for each element in an iterable.

This line called city.title for

each element in cities to create each element in the new list.

Notice this part looks just like the first line of a for loop without a colon,

and the action you want to take on each element is taking on the element here,

and append it to this new list.

In the list comprehension,

we don’t need to create a new list

beforehand and append to it like we would in a for loop.

List comprehensions are not found in other languages,

but are very common in Python.

Here’s another example that creates a list of squares from 0 to 64.

This line called X to the power of two for every element

in range nine to create each element in the new list, squares.

We can write this as a list comprehension like this.

Again, we are just looping through each element in

this iterable and evaluating this expression to get each new element in our list.

You can also add conditionals to list comprehensions.

After the iterable, you can use the If keyword to check a condition in each iteration.

In this example, X to the power of two is only evaluated if X is even.

This gives us a list only including squares of even numbers.

If you want to add an Else,

you will get a syntax error doing this.

If you’d like to add Else,

you have to move the conditionals to the beginning of

the list comprehension right after the expression like this.

Details on why this is the case are in the notes below.

Python에서는 목록을 정말 빠르게 생성하고

List Comprehensions라는 멋진 도구로 간결하게.

이전의 도시 예시에서,

for 루프의 도시 목록에서 대문자로 표시된 도시 목록을 만들었습니다.

목록 이해와 함께,

우리는 이와 같은 결과를 얻을 수 있습니다.

목록 이해를 사용하면 for 루프를 사용하여 한 번에 목록을 만들 수 있습니다.

다음을 포함하는 대괄호로 목록 이해를 만듭니다.

iterable의 각 요소에 대해 평가할 표현식입니다.

city.title 이라는 라인은

도시의 각 요소를 사용하여 새 목록의 각 요소를 만듭니다.

이 부분은 콜론이 없는 for 루프의 첫 번째 줄과 같습니다.

각 요소에 대해 수행하려는 작업은 여기에서 요소에 대해 수행하고 있습니다.

이 새 목록에 추가합니다.

목록 이해에서,

새 목록을 만들 필요가 없습니다

for 루프에서와 같이 미리 추가하고 추가합니다.

목록 이해는 다른 언어에서 찾을 수 없습니다.

그러나 파이썬에서는 매우 일반적입니다.

다음은 0에서 64까지의 사각형 목록을 만드는 또 다른 예입니다.

이 선은 X라고 하는 모든 요소에 대해 2의 거듭제곱입니다.

범위 9에서 새 목록인 사각형의 각 요소를 만듭니다.

우리는 이것을 이와 같은 목록 이해로 작성할 수 있습니다.

다시 말하지만, 우리는 각 요소를 반복하고 있습니다.

이 반복 가능하고 이 표현식을 평가하여 목록에 있는 각각의 새 요소를 가져옵니다.

조건문을 추가하여 내포를 나열할 수도 있습니다.

iterable 후에 If 키워드를 사용하여 각 반복의 조건을 확인할 수 있습니다.

이 예에서 X의 2제곱은 X가 짝수인 경우에만 평가됩니다.

이것은 짝수의 제곱만 포함하는 목록을 제공합니다.

Else를 추가하려면,

이렇게 하면 구문 오류가 발생합니다.

Else를 추가하고 싶다면,

조건문을 시작 부분으로 이동해야 합니다.

다음과 같은 표현식 바로 뒤에 목록 이해가 있습니다.

왜 그런지에 대한 자세한 내용은 아래 메모에 나와 있습니다.

List Comprehensions

In Python, you can create lists really quickly and concisely with list comprehensions. This example from earlier:

capitalized_cities = []
for city in cities:
    capitalized_cities.append(city.title())

can be reduced to:

capitalized_cities = [city.title() for city in cities]

List comprehensions allow us to create a list using a for loop in one step.

You create a list comprehension with brackets [], including an expression to evaluate for each element in an iterable. This list comprehension above calls city.title() for each element city in cities, to create each element in the new list, capitalized_cities.

Conditionals in List Comprehensions

You can also add conditionals to list comprehensions (listcomps). After the iterable, you can use the if keyword to check a condition in each iteration.

squares = [x**2 for x in range(9) if x

The code above sets squares equal to the list [0, 4, 16, 36, 64], as x to the power of 2 is only evaluated if x is even. If you want to add an else, you will get a syntax error doing this.

squares = [x**2 for x in range(9) if x

If you would like to add else, you have to move the conditionals to the beginning of the listcomp, right after the expression, like this.

squares = [x**2 if x

List comprehensions are not found in other languages, but are very common in Python.

%d