Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

데이터분석 공부하기

[Loop] For문으로 List 반복문 만들기 본문

Python

[Loop] For문으로 List 반복문 만들기

Eileen's 2021. 10. 19. 15:34

[반복문]

어떤 '조건'이나 '범위' 내에서 어떤 명령을 '반복적'으로 수행

 

* For문 :

-'범위' -> Sequence

-Sequence의 원소를 하나씩 변수에 넣어가면서 '원소로 반복'하는 방법

for 변수 in 시퀀스: 

      <수행 명령>

 

 

-반복 시 ' 횟수'만 아는 경우 (for-range)

1) 범위를 아는 경우: range(a,b): a부터 b-1까지

2) 횟수를 아는 경우: range(a): 0부터 a-1까지

 

-len(): sequence의 원소 수만큼 실행 

 

 

[LIST]

1) element그대로 받는 경우, for이후 변수(i이던 fruit이던)에 바로 element가 들어간다.

fruits = ['apple', 'grape', 'banana']

1) for fruit in fruits:

print(fruit)

>>> apple grape banana

2) for i in fruits:

print(i)

>>> apple grape banana

 

 

2) range(len()): 

세가지 항목이 있는 list의 len은 3이고, range(3)은 0, 1, 2이다(index로 돌아가는 것과 같은 형태)

fruits = ['apple', 'grape', 'banana']

for fruit in range(len(fruits)):

print(fruit)

>>>0 1 2

*range(list)는 작동 불가: range(1,5)와 같이 범위 또는, range(5)와 같이 횟수 인자를 받음

 

 

3) 'enumerate': index, value 모두 반환

-> 첫번째 변수를 index로 받고, 두번째 변수를 element로 받는다.

*이때 변수의 명칭은 자유 : i , fruit의 위치가 서로 달라도 첫번째 변수가 index, 두번째가 element를 받음

fruits = ['apple', 'grape', 'banana'] 

for i, fruit in enumerate(fruits): 

print(i, fruit)

>>>0 apple 1 grape 2 banana