티스토리 뷰
1. 숫자형 : 숫자 형태로 이루어진 자료형(정수, 실수, 8진수, 16진수)
2. 문자열 자료형 : 문자들의 집합 (" ", ' ', """ """, ''' ''')
3. 리스트 자료형 : 리스트명 = [요소1, 요소2, 요소3,...]
- 리스트 관련 함수
1) append() : 리스트의 마지막 요소를 추가
students = ["stu1","stu2","stu3","stu4"]
# 리스트에 요소 추가 append()
students.append("stu5")
print(students) # ["stu1","stu2","stu3","stu4","stu5"] 출력
2) sort() : 리스트의 요소를 순서대로 정렬
# 리스트 정렬 sort()
students.sort()
print(students) # ["stu1","stu2","stu3","stu4","stu5"] 출력
numderList = [5,2,1,6,7,8,2,10]
numderList.sort()
print(numderList) # [1,2,5,6,7,8,10] 출력
3) reverse() : 리스트 뒤집기
# 리스트 뒤집기 reverse()
students.reverse()
print(students) # ["stu5","stu4","stu3","stu2","stu1"] 출력
4) index() : 리스트에 해당 값이 있으면 그 값의 인덱스 값을 리턴, 없으면 오류발생
# 인덱스 반환 index(value)
num1 = students.index("stu3")
print(num1) # 2 출력
# 없는 인덱스 찾을시 => 오류 발생
# num2 = students.index("stu10")
# print(num2)
5) insert(start, value) : 리스트에 요소 삽입 (start번째에 value를 삽입)
# 리스트에 요소 추가(원하는 위치) insert(start,value)
students.insert(1, "newStu")
print(students) # ["stu1", "newStu", "stu2","stu3","stu4","stu5"] 출력
6) remove(값) : 리스트에서 첫 번째로 나오는 값 하나를 삭제
# 리스트 요소 제거 remove(value)
students.remove("newStu")
print(students) # ["stu1","stu2","stu3","stu4","stu5"] 출력
numderList.remove(2)
print(numderList) # [1,5,6,7,8,10] 출력
7) pop() : 리스트의 맨 마지막 요소를 리턴하고, 그 요소는 삭제
# 리스트 마지막 요소 리턴 후 삭제 pop()
lastList = students.pop()
print(lastList) # "stu5" 출력
print(students) # ["stu1","stu2","stu3","stu4"] 출력
8) count(값) : 리스트 안에 값이 몇 개 있는지 개수를 리턴
# 리스트에 포함된 요소의 개수 세기 count(value)
fruits = ["사과","딸기","사과","바나나","사과", "귤"]
applenum = fruits.count("사과")
print(applenum) # 3 출력
4. 듀플 자료형 : 리스트 자료형과 유사, 소괄호 사용 (요소값 수정, 삭제 불가능)
- 듀플 기본 문법
# 듀플은 소괄호() 사용 !
t = ()
t1 = (1,2,3)
print(t1) # (1,2,3) 출력
# 값이 하나일 때는 쉼표를 찍어줘야 함
t2 = (1,)
print(t2) # (1,) 출력
# 소괄호를 생략해도 된다
t3 = 1,2,3
print(type(t3)) # <class 'tuple'> 출력
- 듀플에 요소 수정이나 삭제하기
# 요소값에 접근해 수정하거나,
t3[0] = 10
# 삭제하려 하면
del t3[0]
print(t3) # 오류남 !!
- 듀플 다루기 (인덱싱, 슬라이싱, +, *, 길이 구하기 len() 메소드)
# 듀플 인덱싱
print(t3[2]) # 3 출력
# 듀플 슬라이싱
print(t3[0:2]) # (1,2) 출력
# 듀플 더하기
print(t1 + t3) # (1,2,3,1,2,3) 출력
# 듀플 곱하기
print(t1 * 3) # (1,2,3,1,2,3,1,2,3) 출력
# 듀플 길이 구하기 len() 메소드
print(len(t1)) # 3 출력
5. 딕셔너리 자료형 : { 'key': value } 형태
- 딕셔너리 기본 문법
dic1 = {'name' : 'green', 'phone' : '01012345678', 'age' : 30} # 기본 딕셔너리
dic2 = {1 : 'a', 2 : 'b', 3 : 'c'} # key값에 숫자가 와도 됨!
# 속성 추가하기
dic1['isJob'] = True
print(dic1) # {'name': 'green', 'phone': '01012345678', 'age': 30, 'isJob': True} 출력
dic2[4] = 'd'
print(dic2) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'} 출력
# value값 접근하기
print(dic1['name']) # green 출력
# 속성 삭제하기
del dic1['phone']
print(dic1) # {'name': 'green', 'age': 30, 'isJob': True} 출력
# key값이 중복될 시, 맨 뒤에 있던 key값으로 덮어 씌워짐
dic3 = {'name': 'blue', 'age': 20, 'name': 'pink'}
print(dic3) # {'name': 'pink', 'age': 20} 출력
- 딕셔너리 관련 함수
1) keys() : key값들만 리스트로 만들기 (파이썬 2.7버전까지만 리스트로 돌려줌, 그 이후는 dic_keys객체로 돌려줌)
구문 → 딕셔너리.keys() / 객체로 돌려줄 때 리스트로 형 변환 하기 print(list(딕셔너리))
# key 리스트 만들기
dic3key = dic3.keys()
print(dic3key) # dict_keys(['name', 'age']) 출력
# 리스트 타입으로 형 변환 list()
dic3keyList = list(dic3key)
print(dic3keyList) # ['name', 'age'] 출력
2) values() : value값들만 리스트로 만들기 (파이썬 2.7버전까지만 리스트로 돌려줌, 그 이후는 dic_values객체로 돌려줌)
구문 → 딕셔너리.values() / 객체로 돌려줄 때 리스트로 형 변환 하기 print(list(딕셔너리))
# value 리스트 만들기
dic3value = dic3.values()
print(dic3value) # dict_values(['pinnk', 20]) 출력
# 리스트 타입으로 형 변환 list()
dic3valueList = list(dic3value)
print(dic3valueList) # ['pink', 20] 출력
3) items() : key, value 쌍을 듀플로 묶은 값을 dic_items객체로 돌려줌
구문 → 딕셔너리.items()
# key, value쌍 얻기
dic3item = dic3.items()
print(dic3item) # dick_items([('name', 'pink'), ('age'), 30]) 출력
# 리스트 타입으로 형 변환 list()
dic3itemList = list(dic3item)
print(dic3itemList) # [('name', 'pink'), ('age', 30)] 출력
4) clear() : key, value 쌍 모두 지우기
구문 → 딕셔너리.clear()
# key, value쌍 모두 지우기
dic3.clear()
print(dic3) # {} 출력
5) get(key) : key로 value값 구하기
구문 → 딕셔너리.get(key)
dic4 = {'name' : '구름', 'age' : 3, 'color' : 'white'}
print(dic4.get('name')) # 구름 출력
print(dic4.get('age')) # 3 출력
※ 존재하지 않는 key로 접근 시, 대괄호 표기법과의 차이점
- 대괄호 표기법에서는 key오류가 발생
- get() 에서는 None을 리턴함
# 대괄호 표기법으로 없는 key로 접근 했을 때
print(dic4['play']) # 오류 !!
# get()으로 없는 key로 접근 했을 때
print(dic4.get('play')) # None 출력
6) in : 해당 key가 딕셔너리 안에 있는지 확인 (있으면 True, 없으면 False 리턴)
구문 → 'key' in 딕셔너리
print('name' in dic4) # True 출력
print('play' in dic4) # False 출력
6. 집합 자료형 : 파이썬 2.3부터 지원, 집합에 관련된 것을 쉽게 처리하기 위해 만듬
- 집합 자료형 기본구문 : 중복 허용하지 않고(중복된 값을 제거하고 싶을 때 사용) 순서가 없다.(인덱싱으로 값을 얻을 수 없다.)
s1 = set([1,2,3,4,5])
s2 = set('hello')
print(s1) # {1,2,3,4,5} 출력
print(s2) # {'l','h','e','o'} 출력('l'은 2개라 하나는 출력되지 않음!)
# 인덱스 값으로 접근하고 싶을 때는 리스트로 변환해서 접근
l2 = list(s2)
print(l2[1]) # h 출력
# 중복 제거 하고 싶을 때 (리스트로 변환)
s3 = set([1,2,3,4,1,2,4])
print(s3) # {1,2,3,4} 출력
l3 = list(s3)
print(l3) # [1,2,3,4] 출력
- 집합 자료형 관련 함수
1) add(value) : 값 하나 추가하기
s1.add(20)
print(s1) # {1,2,3,4,20} 출력
2) update([value1, value2,...]) : 값 여러 개 추가하기
s1.update([100, 200, 300])
print(s1) # {1,2,3,4,100,200,300,20}
3) remove(value) : 특정 값 제거하기
s1.remove(100)
print(s1) # {1,2,3,4,200,300,20} 출력
4) 집합1 & 집합2 / 집합1.intersection(집합2) :두 개의 집합 자료형을 만든 후 겹쳐지는 값만 반환하기 (합집합)
numberset1 = set([1,2,3,4,5,6])
numberset2 = set([4,5,6,7,8,9])
print(numberset1 & numberset2) # {4,5,6} 출력
print(numberset1.intersection(numberset2)) # {4,5,6} 출력
5) 집합1 | 집합2 / 집합1.union(집합2) : 두 개의 집합 자료형을 합쳐서 반환하기 (교집합, 중복되는 값은 하나씩만 들어감)
print(numberset1 | numberset2) # {1,2,3,4,5,6,7,8,9} 출력
print(numberset1.union(numberset2)) # {1,2,3,4,5,6,7,8,9} 출력
6) 집합1 - 집합2 / 집합1.difference(집합2) : 집합1에서 집합2를 뺀 값을 반환하기 (차집합)
print(numberset1 - numberset2) # {1,2,3} 출력
print(numberset1.difference(numberset2)) # {1,2,3} 출력
7. 불 자료형 : 참(true)과 거짓(false)을 나타내는 자료형
- 자료형의 참과 거짓 구분하기
- 문자열 자료형 : 빈 문자열이면 False
- 숫자형 : 0은 False, 0이 아닌 숫자는 True
- 리스트, 딕셔너리, 듀플 : 값이 비어져있으면 False, 있으면 True
- None : False
- bool(value) : 불 타입으로 변환
print(bool(0)) # False
print(bool(-1)) # True
print(bool("")) # False
print(bool(" ")) # True
print(bool("a")) # True
print(bool([])) # False
print(bool({})) # False
print(bool(())) # False
'Python' 카테고리의 다른 글
[Python] 파이썬 파일 생성하기 / 내장함수들 (0) | 2023.03.06 |
---|---|
[Python] 파이썬 함수 (0) | 2023.03.03 |
[Python] 파이썬 제어문 (0) | 2023.03.02 |