-
[Python Programming 기초] # 조건문과 반복문 3 : forProgramming Language/Python 2020. 11. 18. 00:27
# 조건문과 반복문
3. for
: 순회 가능한 객체를 순회하면서 값을 처리할 때 사용
※ 순회 가능한 객체란?
리스트, 문자열, 딕셔너리
특히 딕셔너리의 경우, 순회하면 기본적으로 Key값만 가져옴
∴ Value값 순회 시 dict.values() 이용
or
for key, value in dict.items(): # Key, Value 튜플
print(key, value)
를 사용하자!
ex) a = [1, 2, 4, 3, 5]
for i in a: # i는 관례적으로 i로 많이 쓰나 임의의 변수이므로 아무거나 사용 가능!
print (i, i*2)
=> 1 2
2 4
4 8
3 6
5 10
- for에서 index 사용하기
: a = [1, 2, 4, 3, 5]
for index, num in enumerate(a):
print(index, num)
=> 0 1
1 2
2 3
3 4
4 5
- break, continue 사용 가능!
- 구구단 만들기 (for문 중첩)
x = [2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in x:
for j in y:
print(i, 'x', j, '=', i*j)
- len() : collection의 길이
- range() : 범위를 선택해 리스트를 만드는 함수, 범위는 [_, _)로 적용 → 왼쪽 값(포함)부터 ~ 오른쪽 값(미포함)까지
ex) a = list(range(1, 101))
print(a)
=> [1, 2, ..., 100]
ex) list(range(1, 101, 5)) # 세번째 값은 increment
=> [1, 6, 11, ..., 96]
본 포스팅은 Fast Campus 머신러닝과 데이터 분석 A-Z 강의를
듣고 정리한 내용을 담고 있습니다.
'Programming Language > Python' 카테고리의 다른 글
[Python Programming 기초] # 함수의 이해 및 사용 2 : lambda 함수 (0) 2020.11.18 [Python Programming 기초] # 함수의 이해 및 사용 1 : def (0) 2020.11.18 [Python Programming 기초] # 조건문과 반복문 2 : while (0) 2020.11.18 [Python Programming 기초] # 조건문과 반복문 1 : if (0) 2020.11.18 [Python Programming 기초] # 컬렉션 타입의 이해 4 : Set (0) 2020.11.18