bool) 자료형은 참(True), 거짓(False)을 나타내는 자료형이다 print(bool(1)) # 결괏값: True
print(bool('abcd')) # 결괏값: True
print(bool(0)) # 결괏값: False
print(bool(None)) # 결괏값: False
>, <, <=, >=) print(10 > 20) # 결괏값: False
print(10 < 20) # 결괏값: True
print(10 >= 20)
print(10 <= 20)
==, !=) * == = __eq__ print('Python' == 'python') # 결괏값: False
print('Python' != 'python') # 결괏값: True
print('Python' != 'Python')
print('Python'.__eq__('python')) # 결괏값: False
is, is not) a = 5
b = 5
print(a is b) # 결괏값: True
id())tuple, str, 숫자(int, float...) ▶ '값'이 같으면(==) 'id값' 동일(=) a = 5
b = 5
print(id(a))
print(id(b)) # 객체가 동일하면 id값도 동일하다
and, or, is(객체 동일성)vs==(값)
and : 조건 모두 만족할 때 Trueor : 조건 중 하나만 만족해도 'True`not: 결과 값의 반대를 출력 print(10 == 10 and 1 == True) # True
print(10 > 3 or 0 is False) # True ✔
print(not 10 > 5) # False
print(not 1 == 1.0) # False ✔
print(not 1 is 1.0) # True ✔
'(작은 따옴표), "(큰 따옴표), '''(작은 따옴표 3개), """(큰 따옴표 3개)로 묶어서 출력
여러 줄로 된 문자열(multiline string)
'''(작은 따옴표 3개) or """(큰 따옴표 3개) 사용 print('''해당 상품 재고가
남아있지 않습니다.
재입고를 기다려주세요.
''')
print('''"안녕하세요."
'파이썬'입니다.''')
print(""""Hello"
'Python'""")
print("""Hello, 'Python'""")
\'을 사용 print('Python isn\'t difficult')
\n 사용 print('Python isn\'t \ndifficult')
문자열, 정수, 실수, 불(bool) 등 모든 자료형을 저장할 수 있는 자료 구조
리스트에 저장된 각 값은 요소(element)라고 부른다.
person = ['james', 17, 175.3, True]
range를 사용하여 리스트 만들기 *a=list(): 비어있는 리스트 생성 a = list(range(10))
print(a)
range
a = range(11, -4, -1)
print(list(a))
리스트 안에 문자열을 넣으면?
저장된 요소(element)를 변경, 추가, 삭제할 수 없는 불변형 자료 구조
리스트처럼 문자열, 정수, 실수, 불(bool) 등 여러 자료형 저장 가능
a = 10, False, 'b' ***
b = (10, False, 'b')
print(type(a)) # <class 'tuple'>
print(type(b)) # <class 'tuple'>
print(a is b) # True
a = (3,)
print(type(a)) # <class 'tuple'>
range를 사용하여 튜플 만들기 *a=tuple(): 비어있는 리스트 생성 a = tuple(range(10))
print(a)
a, b, c = [1, 2, 3]
print(a, b, c, sep='\n') # a = 1, b = 2, c = 3 각각 할당
** # unpacking의 또 다른 예시 a, b = map(int, input().split())
연속적으로 이뤄진 자료형(sequence types)
list, tuple, range, str, bytes, bytearray
시퀀스 객체 특징
특장 값 있는지 여부를 확인 가능(in or not in)
a = [0, 10, 20, 30, 40, 50]
print(35 not in a) # True
print(-3 in range(10, -6, 2)) # False
시퀀스 객체를 서로 연결 가능(range는 예외)
a = [0, 10, 20]
b = [9, 8, 7]
print(a+b) # [0, 10, 20, 9, 8, 7]
c = 'snow'
d = 'ball'
print(c+d) # snowball
반복 가능
*연산자는 시퀀스 객체를 특정 횟수만큼 반복하여 새로운 시퀀스 객체를 생성(rangeX)a = [0, 10, 20]
print(a*3) # [0, 10, 20, 0, 10, 20, 0, 10, 20]
# id값도 다름
len()list와 tuple의 요소 개수를 구해줌range의 숫자 생성 개수를 구해줌str의 길이를 구해줌 a = [0, 10, 20, 30, 40, 50, 60]
b = list(range(1,51, 3))
c = 'Hello world!'
print(len(a)) # 7
print(len(b)) # 17
print(len(c)) # 12
UTF-8 문자열의 바이트 수 구하기
UTF-8 인코딩으로 저장하는데, 문자열이 차지하는 실제 바이트 수를 구하는 방법은 다음과 같다. hello = '안녕하세요'
print(len(hello.encode('UTF-8')))
인코딩 vs 디코딩
인코딩
UTF-8, EUC-KR 형식의 byte코드로 변환하는 것을 의미str(문자열).encode('UTF-8') ▶ 해당 문자열을 UTF-8형식의 byte코드로 변환디코딩
byte코드.encode('UTF-8') ▶ UTF-8 byte코드를 유니코드(문자열)로 변환인덱싱(list, range ,str 모두 접근 가능)
음수 인덱싱("-1"부터 시작)
a = [0, 10, 20, 30, 40, 50, 60]
b = list(range(1,51, 3))
c = 'Hello world!'
print(a[1]) # 10
print(b[1]) # 4
print(c[-1]) # !
a = [0, 10, 20, 30, 40, 50, 60]
print(a.__getitem__(2))
IndexError
마지막 요소에 접근하기
a = [0, 10, 20, 30, 40, 50, 60]
target = a[len(a)-1]
print(target)
listO, tupleX, rangeX, strX) *이유: str, tuple, range는 immutable객체 a = [0, 10, 20, 30, 40, 50, 60]
a[2] = 5
listO, tupleX, rangeX, strX) a = [0, 10, 20, 30, 40, 50, 60]
del a[2]
시퀀스 객체의 일부를 잘라서 새로운 시퀀스 객체를 만듦
*주의: 슬라이스의 끝 인덱스 요소는 가져오는 값에 포함X
a = [0, 10, 20, 30, 40, 50, 60]
print(a[1:3]) # [10, 20]
print(a[0:-2]) # [0, 10, 20, 30, 40]
a = [0, 10, 20, 30, 40, 50, 60]
print(a[0:-2:2]) # [0, 20, 40]
a = [0, 10, 20, 30, 40, 50, 60]
print(a[::-1]) # [80, 70, 60, 50, 40, 30, 20, 10, 0]
a = [0, 10, 20, 30, 40, 50, 60, 70, 80]
print(a[::2]) # [0, 20, 40, 60, 80]
print(a[2:8:3]) # [20, 50,]
len() 응용 a = [0, 10, 20, 30, 40, 50, 60, 70, 80]
print(a[:len(a)]) # 리스트 전체를 가져옴
슬라이스에 요소 할당하기(listO, tupleX, rangeX, strX)
할당 요소가 많아지면 list 전체 요소 개수도 증가
할당 요소가 적어지면 list 전체 요소 개수도 감소
*주의: 증가폭을 설정했을 경우, 슬라이스된 요소의 개수와 할당 요소의 개수가 일치해야 함
a = [0, 10, 20, 30, 40, 50, 60, 70, 80]
a[2:5] = [2, 'apple', True, False] # [0, 10, 2, 'apple', True, False, 50, 60, 70, 80]
a[2:7:2] = ['1', True, ] # error
딕셔너리 만들기
key : value 형태
key-value-pair: key와 value는 1:1 대응
key가 중복되는 경우value만 사용딕셔너리 키의 자료형
str, int, float, bool, tuple 등 list와 dict를 제외한 자료형만 가능
value에는 모든 자료형 가능
a = {(2,3):5} # 정상 처리
a = {[2,3]:5} # TypeError
x = {}
y = dict()
dict()로 딕셔너리 만들기'
dict()는 다음과 같이 키와 값을 연결하거나, 리스트, 튜플, 딕셔너리로 딕셔너리를 만들 때 사용딕셔너리 = dict(키1=값1, 키2=값2) # key가 str type인 경우 따옴표 제거하고 입력
딕셔너리 = dict(zip([키1, 키2], [값1, 값2]))
딕셔너리 = dict([(키1, 값1), (키2, 값2)])
딕셔너리 = dict({키1: 값1, 키2: 값2})
lux1 = dict(health=490, mana=334, melee=550)
lux2 = dict(zip(['health', 'mana', 'melee'], [490, 334, 550]))
lux3 = dict([('health', 490), ('mana', 334), ('melle', 550)])
lux4 = dict({'health': 490, 'mana':334, 'melle':550})
딕셔너리 키에 값 할당하기
딕셔너리[key] = 지정할 값(value)
lux1 = dict(health=490, mana=334, melee=550)
lux1['strength'] = 210 # {'health': 490, 'mana': 334, 'melee': 550, 'strength': 210}
key in 딕셔너리
lux1 = dict(health=490, mana=334, melee=550)
lux1['strength'] = 210
print('mana' in lux1) # True
딕셔너리는
해시(Hash)기법을 이용해서 데이터를 저장.해시(Hash)는 (key,value)로 데이터를 저장하는 자료구조를 뜻하며, 해시 맵, 해시테이블 등으로 부르기도 한다. 빠르게 데이터를 검색할 수 있는 것이 장점이다.
딕셔너리의 길이: 딕셔너리의 key 개수
lux1 = dict(health=490, mana=334, melee=550)
lux1['strength'] = 210
print(len(lux1)) # 4