Python/개요 및 문법

컬렉션과 반복문

Bambi97 2024. 9. 26. 11:12

1. 리스트 반복

# 기본 순회
li1 = ['apple', 'banana', 'orange', 'melon']

for i in li1:
  print(i, end=' ')
  
# <결과 콘솔>
# apple banana orange melon 


# score 리스트에 저장된 점수가 60점 이상인 갯수가 몇개인지 확인하는 프로그램
score = [90,30,50,60,80,70,100,40,20,10]
count = 0
for s in score:
  if s >= 60:
    count += 1
print(f'60점 이상인 점수 {count}개 있음')

# <결과 콘솔>
# 60점 이상인 점수 5개 있음

 

2. 딕셔너리 반복

dic1 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-0000-0000'}

# 딕셔너리는 for문 사용시 keys()를 안해도 키만 읽어진다.
for i in dic1:
  print(i, end = ' ') # no userid name hp

for i in dic1:
  print(dic1[i], end = ' ') # 1 apple 김사과 010-0000-0000

for i in dic1.items():
  print(i)
# ('no', 1)
# ('userid', 'apple')
# ('name', '김사과')
# ('hp', '010-0000-0000')

for k, v in dic1.items():
  print(k, v)
# 'no' 1
# 'userid' 'apple'
# 'name' '김사과'
# 'hp' '010-0000-0000'

 

3. 컴프리헨션(Comprehension)

파이썬 리스트, 세트, 딕셔너리를 간단하게 생성하거나 변형하는 방법 (변형 기능이 있기에 튜플은 취급하지 않는다.)

반복 및 조건문을 사용하여 컬렉션을 생성하기에 코드 가독성을 좋게 해준다.

 

(1) 리스트 컴프리헨션

# 리스트 컴프리헨션
num = 10
result = [0 for i in range(num)]
print(result) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

result1 = [i for i in range(num)]
print(result1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

li1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
result2 = [i for i in li1]
print(result2) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

 

*조건 컴프리헨션

* 중첩 반복 컴프리헨션

 

(2) 세트 컴프리헨션

# 세트 컴프리헨션 예제
num = [1,2,3,4,5,2,3,5]
unique_num = set(num)
print(unique_num) # {1, 2, 3, 4, 5}

num2 = [1,2,3,4,5,2,3,5]
unique_num = {i for i in num}
print(unique_num) # {1, 2, 3, 4, 5}

 

(3) 딕셔너리 컴프리헨션

# 딕셔너리 컴프리헨션 예제
names = ['apple', 'banana', 'orange']
# {'apple':5, 'banana':6, 'orange':6} 형태 만들기
name_lengths = {name:len(name) for name in names}
print(name_lengths) # {'apple': 5, 'banana': 6, 'orange': 6}

'Python > 개요 및 문법' 카테고리의 다른 글

콜백함수와 람다함수  (0) 2024.09.26
사용자 정의 함수  (0) 2024.09.26
제어문 - 반복문  (0) 2024.09.25
제어문 - 조건문  (1) 2024.09.25
파이썬 연산자  (0) 2024.09.24