[Python] for 1

yuuforest·2023년 6월 23일
0

Python 문법

목록 보기
4/17
post-thumbnail

range, 배열, enumerate, reversed

🌼 range


✔️ range(숫자)

for num in range(5):
	print(num)
    
>> 0
>> 1
>> 2
>> 3
>> 4

✔️ range(시작, 마지막)

for num in range(3, 7):
	print(num)

>> 3
>> 4
>> 5
>> 6

✔️ range(시작, 마지막, 차이)

for num in range(3, 10, 2):
	print(num)

>> 3
>> 5
>> 7
>> 9
for num in range(5, 0, -1):
	print(num)
    
>> 5
>> 4
>> 3
>> 2
>> 1
for num in range(2, -3, -1):
	print(num)
    
>> 2
>> -1
>> 0 
>> -1
>> -2

🌼 배열


[1차원 배열]
✔️ 원소 하나씩 불러오기

list = ["A", "B", "C", 1, "D", 2, 3]

for str in list:
    print(str)
    
>> A
>> B
>> C
>> 1
>> D
>> 2
>> 3

[2차원 배열]
✔️

N = [[1, 2, 3], [4, 5, 6]]

for num in N:
    print(num)
    
>> [1, 2, 3]
>> [4, 5, 6]
N = [[1, 2, 3], [4, 5, 6]]

for num in range(0, len(N)):
    print(N[num])
    
>> [1, 2, 3]
>> [4, 5, 6]

✔️ 원소 하나씩

N = [[1, 2, 3], [4, 5, 6]]

for r in range(0, len(N)):
    for c in range(0, len(N[r])):
        print(N[r][c])
        
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6
N = [[1, 2, 3], [4, 5, 6]]

for row in N:
    for el in row:
        print(el)
        
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6        
N = [[1, 2, 3], [4, 5, 6]]

for num in N:
    x, y, z = num
    print("x = ", x, ", ", "y = ", y, ", ", "z = ", z)
    
>> x =  1 ,  y =  2 ,  z =  3
>> x =  4 ,  y =  5 ,  z =  6    

🌼 enumerate


✔️ 1개의 리스트

list = ["A", "B", "C", 1, "D", 2, 3]

for num, str in enumerate(list):
    print(num, ":", str)
    
>> 0 : A
>> 1 : B
>> 2 : C
>> 3 : 1
>> 4 : D
>> 5 : 2
>> 6 : 3

✔️ 2개의 리스트

N1 = [1, 2, 3, 4, 5]
N2 = ["하나", "둘", "셋", "넷", "다섯"]

for idx, (n1, n2) in enumerate(zip(N1, N2)):
    print(idx, n1, n2)
    
>> 0 1 하나
>> 1 2>> 2 3>> 3 4>> 4 5 다섯
N1 = [1, 2, 3, 4, 5, 6, 7]
N2 = ["하나", "둘", "셋", "넷", "다섯"]

for idx, (n1, n2) in enumerate(zip(N1, N2)):
    print(idx, n1, n2)		# 길이가 다르면, 짧은 리스트에 맞춰서 출력
    
>> 0 1 하나
>> 1 2>> 2 3>> 3 4>> 4 5 다섯

🌼 reversed


✔️ range

for num in reversed(range(5)):
    print(num)
    
>> 4
>> 3
>> 2
>> 1
>> 0
for num in reversed(range(2, 8, 2)):
    print(num)
    
>> 6
>> 4
>> 2
for num in reversed(range(5, -3, -2)):
    print(num)
    
>> -1
>> 1
>> 3
>> 5

✔️ 배열

N = [2, 3, 4, 5, 6]

for num in reversed(N):
    print(num)
    
>> 6
>> 5
>> 4
>> 3
>> 2

profile
🐥 Backend Developer 🐥

0개의 댓글