python for문
for <원소> in <목록>:
Python은 for in 문만 있음.
<원소> loop variable. <목록>객체내에 원소들이 하나씩 할당
<목록> 거의 모든 타입 사용 . list, tuple, string, iterator, generator, range()
와 len()
내장 함수
>>>for item in iterable: 반복할 구문 >>> for letter in ['A', 'B', 'C']: ... print(letter) ... A B C # loop가 돌면서 어떻게 index와 element에 동시에 접근가능할까. => enumerate()활용 >>> for entry in enumerate(['A', 'B', 'C']): print(entry) (0, 'A') (1, 'B') (2, 'C') >>> for i, letter in enumerate(['A', 'B', 'C']): print(i, letter) 0 A 1 B 2 C >>> for i, letter in enumerate(['A', 'B', 'C'], start=6): print(i, letter) 6 A 7 B 8 C
>>> # iter() 작동원리 >>> iter_letters = iter(['A', 'B', 'C']) >>> next(iter_letters) 'A' >>> next(iter_letters) 'B' >>> next(iter_letters) 'C' >>> # enumerate() 작동원리 >>> iter_letters = iter(['A', 'B', 'C']) >>> next(iter_letters) (0, 'A') >>> next(iter_letters) (1, 'B') >>> next(iter_letters) (2, 'C')
iterable
list
val= [1,2,3] ### Int for i in val: print(i) # 1 # 2 # 3 ### List [i for i in val] #[1, 2, 3, 4, 5, 6]
range
val = range(1,3) for i in val: print(i)
enumerate 내장 함수로 for 루프 돌리기
myList = [1,2,3] myTuple = (1,2,3) mySet = {1,2,3} myStr = "123" myDict= {"1":'a', "2":'b', "3":'c'}
인덱스 번호와 컬렉션의 원소를 tuple형태로 반환 (일일이 세다)
for i in enumerate(myList): print(i) for i in enumerate(myTuple): print(i) for i in enumerate(mySet): print(i) # (0, 1) # (1, 2) # (2, 3)
for i in enumerate(myStr): print(i) for i in enumerate(myDict): print(i) # (0, '1') # (1, '2') # (2, '3')
https://www.daleseo.com/python-enumerate/
중첩루프
>>> apart = [[101, 102, 103, 104], [201, 202, 203, 204], [301, 302, 303, 304], [401, 402, 403, 404]] >>> for floor in apart: ... \tfor room in floor: ... \t\tprint("Newpaper delivery: ", room) ... Newpaper delivery: 101 Newpaper delivery: 102 Newpaper delivery: 103 Newpaper delivery: 104 Newpaper delivery: 201 Newpaper delivery: 202 Newpaper delivery: 203 Newpaper delivery: 204 Newpaper delivery: 301 Newpaper delivery: 302 Newpaper delivery: 303 Newpaper delivery: 304 Newpaper delivery: 401 Newpaper delivery: 402 Newpaper delivery: 403 Newpaper delivery: 404
while
>>> i = 0 >>> while i <= 9: ... \tprint(i) ... \ti = i +1 ... 0 1 2 3 4 5 6 7 8 9 >>> i 10
for and if in one line
python-for문-if문-한-줄로-코딩하기
v1 = list(range(10)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] v2 = [list(range(10)), [10,11,12]]
for i in v1: print(i) ==> int for i in v2: for j in i : print(j)
if v < 6 : print(0) else print(1) if v < 6 : print(0) elif v < 10 : print(1) else : print(2)
for i in v : if i==6 : print(i)
[i for i in v1] ==> list [ j for i in v2 for j in i]
print( 0 if v<6 else 1 ) print(0 if v<6 else 1 if v<10 else 2)
[i for i in v if i==6]