파이썬 문법 중 변수와 자료형을 위주로 강의가 진행되었다. 정확히 알고 있는 내용은 생략하고, 조금이라도 헷갈리거나 새로 알게된 부분만 기록하려고 한다.
학습 내용
1. VSCode 단축키(windows)
2. 자료형 - string
3. 자료형 - list
4. 자료형 - set
1.VSCode 단축키(windows)
Ctrl + / ==> 주석
Shift + Alt + 아래키 ==> 해당 행 복사
2.자료형 - string
print() 함수의 매개변수로 삼중 따옴표를 사용하면 문자열 여러 줄을 전달하여 출력할 수 있다.
print("""
세상에서 제일 긴 게 뭘까요?
기차? 기린의 목? 코끼리의 코?
전부 아닙니다.
여러분의 무한한 가능성입니다^^
""")
replace(old, new) : 문자열을 치환하는 메서드이다.
# replace(old_str,new_str)
today = '2025/02/10'
print(today.replace('/','-'))
print(today) # 원본에는 영향을 끼치지 않는다.
2025-02-10
2025/02/10
strip([chars]) :
- 인자는 제거할 문자 집합을 지정하는 문자열이다.
- 문자열의 선행과 후행에서 해당 문자가 제거된 문자열의 복사본을 반환한다.
- 인자를 생략하면 공백을 제거한다.
origin = 'ohgiraffers'
with_white_space = ' oh giraffers '
# 인자 생략 == 공백 제거
print(with_white_space.strip()) # oh giraffers
# ' o'까지 제거
print(with_white_space.strip(' o')) # h giraffers
# 'os' 제거
print(origin.strip('os')) # hgiraffer
# lstrip() - 선행만 제거
print(origin.lstrip('os')) # hgiraffers
# rstrip() - 후행만 제거
print(origin.rstrip('os')) # ohgiraffer
포맷팅
1.
food = '고구마'
count = 7
print('고양이는 겨울철 양식으로 ' + food + str(count) + '개를 저장했습니다.')
print('고양이는 겨울철 양식으로 ', food, str(count), '개를 저장했습니다.')
고양이는 겨울철 양식으로 고구마7개를 저장했습니다.
고양이는 겨울철 양식으로 고구마 7 개를 저장했습니다.
2.
# % 포맷팅
x = 10
y = 123.456
print("x는 %d입니다." % x)
print("y는 %.2f입니다." % y)
x는 10입니다.
y는 123.46입니다.
3.
# str.format()
print("x는 {0}, y는 {1}입니다.".format(x,y))
print("x는 {a}, y는 {b}입니다.".format(a=x,b=y))
x는 10, y는 123.456입니다.
x는 10, y는 123.456입니다.
4.
# f-string
food = '슈크림 붕어빵'
count = 100
result_str = f'고양이는 겨울철 양식으로 {food} {count}개를 먹었습니다.'
print(result_str)
print(f"고양이는 겨울철 양식으로 {food} {count}개를 먹었습니다.")
고양이는 겨울철 양식으로 슈크림 붕어빵 100개를 먹었습니다.
고양이는 겨울철 양식으로 슈크림 붕어빵 100개를 먹었습니다.
3. 자료형 - list
split()을 사용하여 문자열을 구분자 기준으로 분리한 List로 만들 수 있다.
rainbow_str = 'red-orange-yellow-green-blue-navy-purple'
rainbow = rainbow_str.split('-')
print(rainbow)
['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple']
리스트 메서드
리스트 메서드 확인을 위해 사용하는 fruits 배열을 다음과 같이 먼저 선언해둔다.
fruits = ['orange', 'apple','pear','banana','kiwi', 'apple']
- count()
count(값)은 해당 리스트에 인자로 준 값이 몇 개 존재하는지 확인하여 그 수를 반환한다.
print("apple:", fruits.count('apple')) # apple: 2
만약 해당 값이 존재하지 않는다면 0이 반환된다.
print("test:", fruits.count("test")) # test: 0
- index()
index(값)은 리스트에서 인자로 준 값이 몇 번째 인덱스에 존재하는지 확인하여 그 인덱스를 반환한다.
같은 값이 리스트 내에 여러 개 존재하면 가장 처음에 등장하는 값의 인덱스를 반환한다.
print("index:", fruits.index("apple")) # index: 1
만약 해당 값이 존재하지 않는다면 에러가 발생한다.
# print("index:", fruits.index("apple1")) # error 발생
index(값, 인덱스)와 같이 매개변수를 2개 전달할 수 있다.
- 첫 번째 매개변수 '값': 인덱스를 찾을 대상 값
- 두 번째 매개변수 '인덱스': 첫 번째 매개변수로 준 값을 두 번째 매개변수로 준 인덱스 이후 위치에서 탐색
print("index:", fruits.index("apple", 3)) # index: 5
- reverse()
reverse()는 list의 값을 역으로 정렬한다.
fruits.reverse()
print(fruits) # ['apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
추가 설명 (reversed)
lst = [1,2,3,4,5]
lst.reverse()
print(lst)
lst = [1,2,3,4,5]
lst_ = reversed(lst)
print(lst)
print(lst_) #<lst_reverseiterator object at 0x009F0DD0>
for x in lst_:
print(x, end=" ")
print()
- extend()
extend(값)은 list에 배열로 요소를 덧붙여 추가한다.
fruits.extend(['rainbow friut', 'sweet lemon', 'happy apple'])
print(fruits) # ['apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'pineapple', 'rainbow friut', 'sweet lemon', 'happy apple']
- insert()
insert(index, 값)은 list의 원하는 index 위치에 요소를 추가한다.
fruits.insert(0, 'monkey banana')
print(fruits) # ['monkey banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'pineapple', 'rainbow friut', 'sweet lemon', 'happy apple']
- sort()
요소를 정렬하는 메서드로 원본 list에 영향을 준다.
기본적으로 숫자 오름차순, 알파벳의 첫 글자를 기준으로 오름차순 정렬한다.
매개변수로 다양한 옵션을 주어 다른 기준으로 정렬할 수 있다.
# 문자열 길이가 짧은 순으로 정렬
fruits.sort(key=len)
print(fruits) # ['pear', 'kiwi', 'apple', 'apple', 'orange', 'banana', 'pineapple', 'sweet lemon', 'happy apple', 'rainbow friut', 'monkey banana']
# 복합 기준 정렬
# 문자열 길이와 알파벳 순으로 복합 기준 정렬
fruits.sort(key=lambda x:(len(x),x))
print(fruits) # ['kiwi', 'pear', 'apple', 'apple', 'banana', 'orange', 'pineapple', 'happy apple', 'sweet lemon', 'monkey banana', 'rainbow friut']
- remove()
remove(값)은 값에 해당하는 요소를 삭제한다.
이때 해당 요소가 여러 개라면 index가 앞쪽인 요소 한 개만 삭제한다.
temp = fruits.remove('kiwi')
print(temp) # None (해당 메소드 결과로 반환되는 건 없음)
print(fruits) # ['pear', 'apple', 'apple', 'banana', 'orange', 'pineapple', 'happy apple', 'sweet lemon', 'monkey banana', 'rainbow friut']
4.자료형 - set
중복 제거를 위한 set() 함수 활용
#dict
# 키 set구성 | value 중복 제거
dict = {'a':123, 'b':456, 'c':123, 'a':123}
c = set(dict)
print(c) # {'c', 'a', 'b'} 키값만 가지고 set 생성
d = set(dict.values())
print(d) # {456, 123} 중복 제거
가변성을 가진 자료형으로 데이터, 즉 요소를 추가하거나 제거할 수 있다.
ohgiraffers = {'Pig', 'Squirrel', 'Bear', 'gorilla'}
ohgiraffers.remove('korilla') # set의 데이터 중 remove의 값 제거
ohgiraffers.add("Gorilla") # set에 add('값')으로 값을 추가
print(ohgiraffers) # {'Bear', 'Squirrel', 'Gorilla', 'Pig'}
요소를 추가하는 메서드
- add(값) : set의 list에 인자로 전달받은 값을 추가한다.
ohgiraffers = {'Pig', 'Squirrel', 'Bear', 'Gorilla'}
ohgiraffers.add("Elephant")
print(ohgiraffers) # {'Gorilla', 'Squirrel', 'Elephant', 'Pig', 'Bear'}
- update(값) : 요소 값을 추가한다.
배열을 이용해 한번에 여러 개의 값을 추가하는 것도 가능하나, 이때도 중복된 값은 추가되지 않는다.
ohgiraffers = set(["Monkey", "Tiger", "Wolf"])
print(ohgiraffers) # {'Tiger', 'Monkey', 'Wolf'}
ohgiraffers.update(["Monkey", "Wolf", "Tiger", "Squirrel"])
print(ohgiraffers) # {'Tiger', 'Squirrel', 'Monkey', 'Wolf'}
요소를 제거하는 메서드
- remove(값) : 특정 요소를 제거하며, 값이 존재하지 않으면 Error를 발생시킨다.
ohgiraffers = {'Pig', 'Squirrel', 'Bear', 'Gorilla'}
# ohgiraffers.remove('Elephant') # Error 발생
ohgiraffers.remove('Pig')
print(ohgiraffers) # {'Bear', 'Squirrel', 'Gorilla'}
- discard(값) : 특정 요소를 제거하며, 값이 존재하지 않아도 Error가 발생하지 않는다.
ohgiraffers.discard("Elephant")
print(ohgiraffers) # {'Bear', 'Squirrel', 'Gorilla'}
- pop() : 임의의 값을 제거한다.
집합은 순서를 보장하지 않으므로, 어떤 값이 제거될지 예측할 수 없다.
ohgiraffers.pop()
print(ohgiraffers) # {'Squirrel', 'Gorilla'}
- clear()는 모든 값을 제거한다.
ohgiraffers.clear()
print(ohgiraffers) # set()
집합 연산 메서드
# 합집합 union
print(animals.union(st_animals))
print(animals | st_animals)
# 교집합 intersection
print(animals.intersection(st_animals))
print(animals & st_animals)
# 차집합 difference
print(animals.difference(st_animals))
print(animals - st_animals)
# 대칭차집합 symmetric_difference #대칭차집합 = 합집합 - 교집합
print(animals.symmetric_difference(st_animals))
print(animals ^ st_animals)
복사 메서드
- copy() : 대상 set을 복사하여 반환한다.
ohgiraffers = {'Squirrel','Gorilla', 'Tiger', 'Sheep', 'monkey', 'wolf'}
zzap_ohgiraffers = ohgiraffers.copy()
print(ohgiraffers) # {'wolf', 'Sheep', 'Tiger', 'Gorilla', 'monkey', 'Squirrel'}
print(zzap_ohgiraffers) # {'wolf', 'Sheep', 'Tiger', 'Gorilla', 'monkey', 'Squirrel'}
zzap_ohgiraffers.remove('Tiger')
print(ohgiraffers) # {'wolf', 'Sheep', 'Tiger', 'Gorilla', 'monkey', 'Squirrel'}
print(zzap_ohgiraffers) # {'wolf', 'Sheep', 'Gorilla', 'monkey', 'Squirrel'}
'SK Networks AI > 일일 회고록' 카테고리의 다른 글
[SK네트웍스 Family AI 캠프 11기] 일일 회고 - 6일차(25.02.14 금요일) (2) | 2025.02.14 |
---|---|
[SK네트웍스 Family AI 캠프 11기] 일일 회고 - 5일차(25.02.13 목요일) (0) | 2025.02.13 |
[SK네트웍스 Family AI 캠프 11기] 일일 회고 - 4일차(25.02.12 수요일) (0) | 2025.02.12 |
[SK네트웍스 Family AI 캠프 11기] 일일 회고 - 3일차(25.02.11 화요일) (0) | 2025.02.10 |
[SK네트웍스 Family AI 캠프 11기] 일일 회고 - 1일차(25.02.07 금요일) (2) | 2025.02.09 |