파이썬에서는 리스트 컴프리헨션 기능을 제공하는 문법이 있다. 이번 장에서는 리스트 컴프리헨션 기능과 관련된 문법을 정리해보도록 하자.
리스트 컴프리헨션
- list comprehension: 리스트 함축 표현식
- 한 리스트에서 다른 리스트를 만들어내는 간결한 문법
- 리스트 컴프리헨션 예제
파이썬 내장함수 map
- 리스트 컴프리헨션과 같은 기능 제공
- 리스트 컴프리헨션과 다르게 인수가 여러개인 경우도 적용 가능
lambda
함수를 생성해야 하기 때문에 리스트 컴프리헨션보다는 명확하지 못함
- map 예제
조건식 추가
- 리스트 컴프리헨션은 map과 다르게 조건식을 추가할 수 있음
- 조건식 추가 예제
- map도 filter과 연계해서 조건식 추가 가능: but 읽기 어려운 단점
- map 조건식 추가 예제
딕셔너리/세트 컴프리헨션
- 딕셔너리와 세트에도 컴프리헨션에 해당하는 문법 존재
- 컴프리헨션 문법을 사용하면 알고리즘을 작성할 때 파생되는 자료 구조를 쉽게 생성 가능
- 예제
Comments