for x in range(1, 11) :
print(x)
우리는 for 문을 다음과 같이 쓰였다 .
하지만 list comprehension을 이용한 for문을 사용하면 다음과 같이 사용 할수 있습니다 .
list comprehension for문
new_list = [ x for x in range(1, 11) ]
print(new_list)
결과값 -
list comprehension if문
이전 For loops 섹션에서 my_list 에서 홀수 값들을 다음과 같이 골라내서 for loop 바깥에 있는 odd_numbers 라는 리스트에 append 하는 코드가 있었습니다.
odd_numbers = [ ]
for element in range(1,11):
if (element % 2) == 1:
odd_numbers.append(element)
print(odd_numbers)
위코드를 comprehension으로 적용하여 4줄로 만들어보겠습니다 .
```
list_comprehension = [ element for element in range(1,11) if (element % 2) == 1 ]
print(list_comprehension)
이처럼 For 루프 내부에서 새로운 리스트를
만드는 For 루프는 리스트 컴프리헨션으로 변환할 수 있고,
반대로 리스트 컴프리헨션 또한 for문으로 변환할 수 있습니다.
Assignments
1.다음과 같은 도시목록의 리스트가 주어졌을때, 도시이름이
S로 시작하지 않는 도시만 리스트로 만들 때 리스트 컴프리헨션을
사용하여 함수를 작성해 보세요.
cities = ["Tokyo", "Shanghai", "Jakarta", "Seoul",
"Guangzhou","Beijing", "Karachi", "Shenzhen", "Delhi" ]
리스트 컴프리헨션을 사용 안하였을때 .
cities = ["Tokyo","Shanghai","Jakarta","Seoul","Guangzhou","Beijing","Karachi","Shenzhen","Delhi"]
size = len(cities)
a=[]
for i in range(size):
if "S" not in cities[i][0] :
a.append(cities[i])
print(a)
리스트 컴프리헨션을 사용 하였을때
cities = ["Tokyo","Shanghai","Jakarta","Seoul","Guangzhou","Beijing","Karachi","Shenzhen","Delhi"]
list_ex = [ cities[element] for element in range(0,9) if "S" not in cities[element][0]]
print(list_ex)
결과값은 같다 .
2.다음과 같은 도시, 인구수가 튜플의 리스트로 주어졌
을때, 키가 도시, 값이 인구수인 딕셔너리를 딕셔너리
컴프리헨션을 사용한 함수를 작성해 보세요.
population_of_city =
[(‘Tokyo', 36923000), (‘Shanghai', 34000000),
(‘Jakarta', 30000000), (‘Seoul', 25514000),
(‘Guangzhou', 25000000), (‘Beijing', 24900000),
(‘Karachi', 24300000 ), ( ‘Shenzhen', 23300000),
(‘Delhi', 21753486) ]_
컴프리헨션은 사용 x
population_of_city = [('Tokyo', 36923000), ('Shanghai', 34000000), ('Jakarta', 30000000), ('Seoul', 25514000), ('Guangzhou', 25000000), ('Beijing', 24900000),('Karachi', 24300000),( 'Shenzhen', 23300000),('Delhi', 21753486) ]
dict_0={}
sen=len(population_of_city)
for i in range(sen) :
dict_0 [population_of_city[i][0]] = population_of_city[i][1]
print(dict_0)
population_of_city = [('Tokyo', 36923000), ('Shanghai', 34000000), ('Jakarta', 30000000), ('Seoul', 25514000), ('Guangzhou', 25000000), ('Beijing', 24900000),('Karachi', 24300000),( 'Shenzhen', 23300000),('Delhi', 21753486) ]
dict_0={}
사용 -
sen=len(population_of_city)
list_0={population_of_city[i][0]:population_of_city[i][1] for i in range(sen)}
print(list_0)