공실이의 개발 블로그

[Python] List Comprehension 이해하기 본문

Python

[Python] List Comprehension 이해하기

박공실캔따개 2023. 4. 13. 09:53

 Introduction 

 

  • 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.
 

5. Data Structures

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. More on Lists: The list data type has some more methods. Here are all of the method...

docs.python.org

 

  • 리스트 컴프리헨션이란 '리스트 안에 표현식(계산식)과 for문, if문을 한줄에 넣어서 새로운 리스트를 만드는 것'을 말한다. 여기서 리스트라는 말이 들어가서 리스트만 사용할 수 있을 것 같지만, 앞서 배웠던 리스트(list), 튜플(tuple), 딕셔너리(dictionary), 셋트(set) 등의 컨테이너들도 모두 사용가능하다. 또한 표현식엔 수식 뿐만 아니라 함수도 사용 가능한 점도 알고 있으면 훨씬 더 간단한 코딩이 가능하다.
 

[파이썬 중급 문법] 리스트 컴프리헨션 간단 정리

안녕하세요, 왕초보 코린이를 위한 코딩유치원에 오신 것을 환영합니다. 코딩유치원에서는 파이썬 기초부터 사무자동화, 웹크롤링, 데이터 분석 등의 다양한 패키지까지 초보자도 알기 쉽도록

coding-kindergarten.tistory.com

 


 List Comprehension 

 

squares = []
for x in range(10):
    squares.append(x**2)

squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  •  for문을 사용하여 리스트 만드는 방법

 

squares = [x**2 for x in range(10)]
  •  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)]
  •  List Comprehension에 if 조건문을 사용한 예시

 

combs = []
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)]
  • 위의 코드와 결과를 비교하기 위한 일반적인 형태

 


 Nested(중첩) List Comprehensions 

 

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
  • matrix 리스트 생성

 

[[row[i] for row in matrix] for i in range(4)]

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
  • Nested List Comprehension 방법

 

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]]
  • List Comprehension 사용의 이해를 돕기 위한 중간 과정

 

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]]
  • for문을 사용하여 리스트에 내용 추가

 

list(zip(*matrix))

[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
  • zip 함수 사용

 


 

'Python' 카테고리의 다른 글

[Python] 데이터 시각화 - Matplotlib and Seaborn  (0) 2023.04.17