Programming

[혼공파] Iteration

곰나루_ 2023. 12. 31. 17:10

● 1. List & Iteration

  • string과 list는 매우 비슷한 data type이므로, 사용할 수 있는 연산자와 함수도 비슷하다.
  • 비파괴적인 list 연결 연산자와 달리, 파괴적인 아래 함수들은 list 자체를 바꿔버린다.
연산
(비파괴적)
+ 연결
* 반복
len() element 개수 세기
추가 list .append(요소) list 뒤에 추가
list .insert(위치, 요소) list 중간에 추가
list .extend( [요소1, 요소2 ..] ) 한 번에 여러 요소 추가 (매개변수로 list를 입력)
제거 del list [index] 위치 기반 제거 (slicing해 여러 개 제거도 가능)
list .pop(index) 위치 기반 제거  (index 미입력시 -1로 취급해 마지막 요소 제거)
list .remove(data) 특정 값 제거 (가장 먼저 발견되는 하나만 제거)
list .clear() 내부 요소를 모두 제거
정렬 list .sort() 오름차순 정렬 (기본)
list .sort(reverse=True) 내림차순 정렬
내부 확인 data in list 있으면 True, 없으면 False 출력
data not in list 있으면 False, 없으면 True 출력

 

 

- for iteration

for iterator in iterable(string, list, dictionary, range...) :
    반복할 코드
array = [273, 32, 103, 57, 52]

for element in array:
    print(element)
# list의 요소 하나하나가 element라는 변수에 들어가며, 차례차례 반복한다.

 

- [예제 p.211]  2차원 list의 모든 element 출력하기

list_of_list = [
    [1,2,3],
    [4,5,6,7],
    [8,9]
]

for i in list_of_list:
    for j in i:
        print(j)

 

 

- Spread operator (*)

(1) list 내부에 사용  (출력 값은 list)

a = [1,2,3,4]
b = [*a, *a]

print(b)

 

이를 이용하면 비파괴적으로 append() 함수와 같은 결과를 구현할 수 있다.

a = [1,2,3,4]
b = [*a, 5]

print(b)

 

(2) 함수의 매개변수 위치에 사용  (element를 list 밖으로 꺼낼 수 있음)

a = [1,2,3,4]

print(*a)

 

 

- [확인 p.214]  홀짝 판단하기

numbers = [273, 103, 5, 32, 65, 9, 72, 800, 99]

for number in numbers:
    if number % 2 == 0:
        print(f '{ number }는 짝수입니다')
    else:
        print(f '{ number }는 홀수입니다')

 

- [확인 p.214]  자릿수 판단하기

numbers = [273, 103, 5, 32, 65, 9, 72, 800, 99]

for number in numbers:
    print(f '{ number }{len(str( number ))}자릿수입니다')        # 숫자를 string으로 변환한 후, len() 함수를 써준 것!

 

- [확인 p.215]  코드 빈칸 채우기 ★

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = [ [ ], [ ], [ ] ]

for number in numbers:
    output[ ( number + 2) % 3 ].append(number)
    # index 자리에 어떤 수식을 넣어야 원하는 list에 숫자들을 넣을 수 있는지 고민해야 함!!
    # 앞에서 list를 선언할 때의 [ ]와, 여기서 element에 접근할 때의 [index]를 구별해야 한다.

print(output)

 

 

2. Dictionary & Iteration

Data type 의미 선언 형식 요소 접근 형식
List Index를 기반으로 값을 저장 list_a = [ ] list_a [1]
Dictionary Key를 기반으로 값을 저장 dict_a = { } dict_a ["name"]

 

추가 새 key를 기반으로 새 값을 입력하면 된다.
제거 del dict [key] key를 지정해 제거
내부 확인 key in dict key가 있는지 확인
dict .get(key) 있으면 그 key에 해당하는 값을, 없으면 None을 출력

 

 

- [확인 p.227]  dictionary의 list

pets = [
    {"name" : "구름", "age" : 5},
    {"name" : "초코", "age" : 3},
    {"name" : "아지", "age" : 1},
    {"name" : "호랑이", "age" : 1},
]

for pet in pets:
    print(f'{pet["name"]} {pet["age"]}살')

 

- [확인 p.228]  list 내에 같은 숫자가 몇 번 등장하는지 세기

numbers = [1,2,6,8,4,3,2,1,9,5,4,9,7,2,1,3,5,4,8,9,7,2,3]
counter = {}        # 빈 상자 만들어주기

for number in numbers:
    if number in counter:
        counter[ number ] += 1
        # 적어도 한 번 세어본 상황. 따라서 key가 이미 있으므로 숫자만 더해주면 된다.
    else:
        counter[ number ] = 1
        # 한 번도 세지 않은 상황. 따라서 새로운 key를 만들어줘야 한다.

print(counter)

 

- [확인 p.229]  dictionary와 list의 중첩  

풀이 1 - 내 풀이

character = {
    "name" : "기사",
    "level" : 12,
    "items" : {
        "sword" : "불꽃의 검",
        "armor" : "풀블레이트"
    },
    "skill" : ["베기", "세게 베기", "아주 세게 베기"]
}

for i in character:
    if type(character[i]) is dict:
        for j in character[i]:
            print(j, ":", character[i][j])
    elif type(character[i]) is list:
        for j in character[i]:
            print(i, ":", j)
    else:
        print(i, ":", character[i])

 

풀이 2 - 정답지

for key in character:
    if type(character[key]) is dict:
        for small_key in character[key]:
            print(small_key, ":", character[key][small_key])
    elif type(character[key]) is list:
        for item in character[key]:
            print(key, ":", item)
    else:
        print(key, ":", character[key])

 

★ Self Feedback

    "i, j"가 아닌 "key, small_key" 등으로 변수를 설정하는 것이 가독성이 좋아보인다.

 

 

3. Range data type & while iteration

range(A) 0 ~ A-1 (정수)
range(A, B) A ~ B-1
range(A, B, C) A ~ B-1 (단, 숫자 차이가 C만큼씩)

 

- [예제 p.237]  중첩 반복문으로 피라미드 만들기(1) ★

output = ""    # output이라는 라벨이 달린 "빈 상자" 먼저 설정해놓기 (숫자라면 0)

for i in range(1,10):
    for j in range(0,i):
        output += "*"
    output += "\n"

# 바깥 for문 1회차 : (i, j) = (1,0) -> 한 번 실행.
# 바깥 for문 2회차 : (i, j) = (2,0), (2,1) -> 두 번 실행
# 바깥 for문 3회차 : (i, j) = (3,0), (3,1), (3,2) -> 두 번 실행
# ... ...

print(output)

 

- [예제 p.239]  중첩 반복문으로 피라미드 만들기(2) ★

output = ""

for i in range(1, 15):
    for j in range(14, i, -1):
        output += " "
    for k in range(0, 2*i-1):
        output += "*"
    output += "\n"

print(output)

 

 

- while iteration

whie Boolean expression :
        반복할 코드

 

특히 1) 무한 반복을 구현해야 하는 경우, 2) 조건을 활용해 반복해야 하는 경우 등에서 while 반복문을 사용한다.

 

- 반복을 끝내는 키워드

  • break : 무한반복을 벗어날 때
  • continue : 현재 반복을 생략하고, 다음 반복으로 넘어갈 때

 

- [확인 p.248]  list를 조합해 하나의 dictionary 만들기

key_list = ["name", "hp", "mp", "level"]
value_list = ["기사", 200, 30, 5]
character = {}
 
# 두 리스트의 길이가 같으므로, len() 함수를 활용해 필요한 index에 접근한다.
# character의 i번째 key에 i번째 value를 넣는다.
for i in range(0, len(key_list)):
    character[key_list[i]] = value_list[i]

print(character)

 

- [확인 p.248]  limit를 넘을 때까지 정수 더하기

limit = int(input("정수를 입력하세요 : "))
i = 1
sum_value = 0

while sum_value < limit:
    sum_value += i
    i += 1

print("{}를 더할 때 {}를 넘으며 그때의 값은 {}입니다.".format(i-1, limit, sum_value))

 Self Feedback : 무한 반복이 아니므로, break는 넣어줄 필요 없다.

 

- [확인 p.249]  n * (100-n)의 최댓값 찾기

풀이 1 - 내 풀이

max_value = 0
a = 0
b = 0

for i in  range(1,100):
    j = 100 - i

    if i * j >= (i + 1) * (j - 1):
        continue
    else:
        a = i + 1
        b = j - 1
        max_value = a * b

print("최대가 되는 경우 : {} * {} = {}".format(a, b, max_value))

 

풀이 2 - 정답지

max_value = 0
a = 0
b = 0

for i in  range(1,100):
    j = 100 - i
    current = i * j        # 비교를 위해 current라는 상자(변수) 새로 만들기

    if max_value < current :
        a = i
        b = j
        max_value = current        # max_value라는 상자 안에 current 값 새로 집어넣기

print("최대가 되는 경우 : {} * {} = {}".format(a, b, max_value))

★Self Feedback

  1. current라는 변수를 새로 설정해서 if 문에 사용하는 것이 가독성에 더 좋아보인다.
  2. 정답지처럼 현재 값을 먼저 구하고(current), 원하는 값(max_value)과 비교하는 조건문 방식이 더 논리적으로 보인다.

 

 

 

4. string, list, dictionary와 관련된 기본 함수

- 파이썬의 특유한 함수들

함수 사용 예시 의미
min(), max(), sum() sum(list) 최댓값/최솟값/총합
reversed() 출력할때 : list ( reversed(list) )
반복문과 조합 : for i in reversed(list)
list 뒤집기
enumerate() 출력할때 : list ( enumerate(list) )
반복문과 조합 : for i, value in reversed(list)
현재 index가 몇 번째인지 확인
items() dictionary .items() dictionary로 쉽게 반복문 작성
list comprehensions array = [ i * i for i in range(0, 20, 2) ] list 안에 for 문 사용

 

'Programming' 카테고리의 다른 글

git  (0) 2024.01.14
[혼공파] Conditional  (1) 2023.12.15
[혼공파] Data type  (0) 2023.12.14
[생활코딩] CSS  (1) 2023.11.27
[생활코딩] HTML & Internet  (1) 2023.10.28