LIST COMPREHENSION
List comprehension은 기존에 있는 리스트 요소를 가지고 새로운 리스트를 생성하고 싶을 때 사용할 수 있다.
연습
Q. 리스트 fruits 에 철자 'a'가 들어가는 과일만 리스트로 추출하기
1) for문으로 기존 fruits 리스트에 for문에 if문을 사용해서 'a'가 들어가는 요소만 리스트 newlist로 뽑아내기
fruits = ["apple", "banana","melon","grape","cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
2) List comprehension 으로 한 줄 코드로 뽑아내기
fruits = ["apple", "banana","melon","grape","cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
구문비교
newlist = [] for x in fruits: if "a" in x: newlist.append(x) |
newlist = [ x for x in fruits if "a" in x ] |
기존 for문 : 문자열 공백제거해서 리스트로 출력하기
season = 'Spring, Summer, Autumn, Winter' # 문자열
season2 = season.split(',') # 문자열 분리
type(season2) # list
season3 = []
for item in season2:
season3.append(item.strip()) # 양쪽 공백 제거
print(season3)

List comprehension : 문자열
season = 'Spring, Summer, Autumn, Winter' # 문자열
season2 = season.split(',') # 문자열 분리
c = [item.strip() for item in season2] # list comprehension
print(c)

<참고>
https://www.w3schools.com/python/python_lists_comprehension.asp
Python - List Comprehension
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
'Python' 카테고리의 다른 글
[Python] Data type : 딕셔너리(Dictionary) 와 셋(Set) (0) | 2022.08.22 |
---|---|
[Python] 문자열 포맷팅 (0) | 2022.08.21 |
[Python] 클래스(Class)와 객체(Object) (0) | 2022.08.20 |
리스트로 구현하는 자료구조 : Stack(스택)과 Queue(큐) (0) | 2022.08.13 |
[Sol] Powershell에서 tab키 기능 수정하기 (0) | 2022.08.01 |