"리스트 컴프리헨션"의 두 판 사이의 차이

18번째 줄: 18번째 줄:
[[category: Python]]
[[category: Python]]
{{참고|Python 리스트 컴프리헨션}}
{{참고|Python 리스트 컴프리헨션}}
<source lang='Python'>
<source lang='Python' run>
numbers = [1, 2, 3, 4, 5, 6]
numbers = [1, 2, 3, 4, 5, 6]
print( [x * 2 - 1 for x in numbers] )
print( [x * 2 - 1 for x in numbers] )
# [1, 3, 5, 7, 9, 11]
# [1, 3, 5, 7, 9, 11]
</source>
</source>
<source lang='Python'>
<source lang='Python' run>
fruits = ['Apple', 'Banana', 'Orange', 'Mango']
fruits = ['Apple', 'Banana', 'Orange', 'Mango']
print( [len(i) for i in fruits] )
print( [len(i) for i in fruits] )
# [5, 6, 6, 5]
# [5, 6, 6, 5]
</source>
</source>
<source lang='Python'>
<source lang='Python' run>
fruits = ['Apple', 'Banana', 'Orange', 'Mango']
fruits = ['Apple', 'Banana', 'Orange', 'Mango']
print( [v for v in fruits if len(v)>5] )
print( [v for v in fruits if len(v)>5] )
# ['Banana', 'Orange']
# ['Banana', 'Orange']
</source>
</source>
<source lang='Python'>
<source lang='Python' run>
fruits = ['Apple', 'Banana', 'Orange', 'Mango']
fruits = ['Apple', 'Banana', 'Orange', 'Mango']
print( [fruit.upper() for fruit in fruits] )
print( [fruit.upper() for fruit in fruits] )
# ['APPLE', 'BANANA', 'ORANGE', 'MANGO']
# ['APPLE', 'BANANA', 'ORANGE', 'MANGO']
</source>
</source>
<source lang='Python'>
<source lang='Python' run>
print( [i ** 2 for i in range(10)] )
print( [i ** 2 for i in range(10)] )
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</source>
</source>
<source lang='Python'>
<source lang='Python' run>
suits = ('spade', 'heart', 'diamond', 'clover')
suits = ('spade', 'heart', 'diamond', 'clover')
ranks = (1, 2)
ranks = (1, 2)

2020년 7월 11일 (토) 19:24 판

1 개요

list comprehension
리스트 컴프리헨션, 리스트 캄프리헨션
  • 기존의 리스트를 이용하여 새로운 리스트를 만드는 방법
  • 기존의 리스트에 기반한 리스트를 만들기 위해 일부 프로그래밍 언어에서 사용 가능한 문법적 구조
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x**2 for x in a]
print(squares)

2 예제

3 같이 보기

4 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}