본문 바로가기
공부/코딩

⛷ [파이썬] 파이썬 예제 문제모음 : 리스트 내포 (List Comprehension)

by blackb1rd 2022. 11. 11.
728x90
반응형
728x170

 

 

 

파이썬 독학 예제 문제모음

 

 

파이썬 리스트 내포(List Comprehension) 예제 문제모음

 

문제1) 다음 for문을 리스트 내포(list comprehension)로 변경해보세요. 

cities = [ 'Newyork', 'Seoul', 'Milano' ]

cities_a = [ ] 
for c in cities:
    cities_a.append( [ c, len(c) ] )

print(cities_a)

 

결과 값

[['Newyork', 7], ['Seoul', 5], ['Milano', 6]]

 

 

 

 

 

정답

cities = [ 'Newyork', 'Seoul', 'Milano' ]
cities_a_b = [ [ c, len(c) ] for c in cities ]


print(cities_a_b)

 

결과 값

[['Newyork', 7], ['Seoul', 5], ['Milano', 6]]

 

리스트 내포는 원리만 잘 이해 한다면 실제 식에 간단하게 적용할 수 있습니다.

우선 for 문의 가장 마지막 코드cities_a.append ()안에 있는 [ c, len(c) ]를 새로 만든 cities_a_b의 맨 앞에 넣고 for c in cities라는 for문을 그대로 넣으면 됩니다. 

 

다음과 같이 for문을 리스트 내포로 변경하는 가장 큰 이유는 2줄의 코드를 1줄로 줄여 간단하게 표현할 수 있기 때문입니다. 좀 더 난이도 있는 다음 예제들로 리스트 내포로 코드 줄을 줄일 수 있는 여러가지 방법을 공부해보세요. 

 

 

 

 

 

 

문제2) 두개로 작성된 for 문을 하나의 리스트 내포로 다시 작성해보세요. 결과 값은 동일해야 합니다. 

def carl(*l):
    ## 변경 가능한 구역 시작
    line = [ ]
    for li in l:
        for el in li:
            line.append(el)    
    ## 변경 가능한 구역 끝
    return ' '.join( line )

l1 = ['Look', 'again', 'at', 'that', 'dot.' ]    
l2 = [ 'That', 'is', 'here.' ]
l3 = [ 'That', 'is', 'home.' ]

carl( l1, l2, l3 )

 

결과 값

'Look again at that dot. That is here. That is home.'

 

 

 

 

 

정답 

def carl_s(*l): #1
    line = [ el for li in l for el in li ]   
    return ' '.join( line )

l1 = ['Look', 'again', 'at', 'that', 'dot.' ]    
l2 = [ 'That', 'is', 'here.' ]
l3 = [ 'That', 'is', 'home.' ]

carl_s( l1, l2, l3 )

 

결과 값

'Look again at that dot. That is here. That is home.'

 

for문이 1개 이상인 2개인 경우에도 리스트 내포로 식을 변경하는 것은 1개일 때와 동일합니다. 

우선 2개 for를 리스트 내포로 변환할 경우 line.append()안에 있는 el을 line = []의 가장 첫번째에 넣고, 첫번째 for문과 두번째 for문을 차례대로 써주면 됩니다. 

 

 

 

 

반응형

 

 

 

문제3) for문을 사용하여 아래의 리스트 내포를 재작성 해보세요. 결과 값은 일치해야 합니다.  

from string import punctuation

def remove_s( text ):
    text_list = text.split()
    text_list_no_punctuation =  [ word.lower().rstrip( punctuation ) for word in text_list ]
    return text_list_no_punctuation

text = 'The Earth is a very small stage in a vast cosmic arena.'

print( remove_s( text ) )

 

결과 값

['the', 'earth', 'is', 'a', 'very', 'small', 'stage', 'in', 'a', 'vast', 'cosmic', 'arena']

 

 

 

 

 

정답 

from string import punctuation

def remove( text ):
    text_list = text.split()
    text_list_no_punctuation = [ ]
    for word in text_list:
        text_list_no_punctuation.append( word.lower().rstrip( punctuation ) )
    return text_list_no_punctuation

text = 'The Earth is a very small stage in a vast cosmic arena.'

print( remove( text ) )

 

결과 값

['the', 'earth', 'is', 'a', 'very', 'small', 'stage', 'in', 'a', 'vast', 'cosmic', 'arena']

 

문제 속의 리스트 내포를 for문으로 푸는 식을 잘 정리하면 쉽게 풀 수 있는 문제 입니다. 

text_list_no_punctuation =  [ word.lower().rstrip( punctuation ) for word in text_list ]

->    

text_list_no_punctuation = [ ]
for word in text_list:
    text_list_no_punctuation.append( word.lower().rstrip( punctuation ) )

 

 

 

문제4) for문을 리스트 내포로 변환해보세요.  결과 값은 동일해야 합니다. 

years = [ 3, 5 ]
sources = [ [ 'Soy' ],  [ 'Sesame' ], [ 'Tomato' ], [ 'Chilli'] ]

pairs = []
for age in years:
    for ingredient in sources:
        pairs.append( [ ingredient , age ] ) 

print(pairs)

 

결과 값

[[['Soy'], 3], [['Sesame'], 3], [['Tomato'], 3], [['Chilli'], 3], [['Soy'], 5], [['Sesame'], 5], [['Tomato'], 5], [['Chilli'], 5]]

 

 

 

 

 

정답 

years = [ 3, 5 ]
sources = [ [ 'Soy' ],  [ 'Sesame' ], [ 'Tomato' ], [ 'Chilli'] ]

pairs = [[ingredient , age] for age in years for ingredient in sources]

print(pairs)

 

결과 값

[[['Soy'], 3], [['Sesame'], 3], [['Tomato'], 3], [['Chilli'], 3], [['Soy'], 5], [['Sesame'], 5], [['Tomato'], 5], [['Chilli'], 5]]

 

 

 

 

728x90
반응형
그리드형

댓글