1. 자료형
(1) 리스트, 튜플
- 리스트 특징
# Section04-3
# 파이썬 데이터 타입(자료형)
# 리스트, 튜플
# 리스트 자료형(순서O, 중복O, 수정O, 삭제O)
# 선언
a = []
b = list()
c = [1, 2, 3, 4]
d = [10, 100, 'Pen', 'Cap', 'Plate']
e = [10, 100, ['Pen', 'Cap', 'Plate']]
# 인덱싱
음수는 뒤에서부터(0부터가 아니라 -1부터)
print('#=====#')
print('d - ', type(d), d)
print('d - ', d[1])
print('d - ', d[0] + d[1] + d[1])
print('d - ', d[-1])
print('e - ', e[-1][1])
print('e - ', e[-1][1][4])
print('e - ', list(e[-1][1]))
# 슬라이싱
마지막만 빼고 나온다
print('#=====#')
print('d - ', d[0:3]) // 0번째 ~ 2번째
print('d - ', d[2:])
print('e - ', e[2][1:3])
# 리스트 연산
print('#=====#')
print('c + d - ', c + d) // c, d의 요소를 모두 가진 리스트가 나온다
print('c * 3 - ', c * 3) // c의 요소가 순서대로 3번씩 반복해서 나온다
# print("c[0] + 'hi' - ",c[0] + 'hi')
print("'hi' + c[0] - ", 'hi' + str(c[0]))
# 리스트 수정, 삭제
print('#=====#')
c[0] = 4 // 0번째가 4가 된다
print('c - ', c)
c[1:2] = ['a', 'b', 'c']// 1번째에 원소들이 들어가고 뒤에 있는 원소들이 더 뒤로 밀려난다
print('c - ', c)
c[1] = ['a', 'b', 'c'] // 인덱싱으로 넣으면 리스트가 원소로 들어간다
c = [1, ['a', 'b', 'c'] , 2, 3, 4]
print('c - ', c)
c[1:3] = []
print('c - ', c)
del c[3] // 원소 삭제하는 방법
print('c - ', c)
# 리스트 함수
a = [5, 2, 3, 1, 4]
print('a - ', a)
a.append(6) // 끝부분에 추가
print('a - ', a)
a.sort() //순서대로 정렬
print('a - ', a)
a.reverse() //역순으로 정렬
print('a - ', a)
print('a - ', a.index(5))
a.insert(2, 7) // 2번 인덱스에 7을 삽입
print('a - ', a)
a.reverse()
a.remove(1)// del c[2]는 인덱싱으로 삭제, romove는 해당 값을 삭제
print('a - ', a)
print('a - ', a.pop()) // 마지막에 있는 원소를 뺀 나머지가 나온다
print('a - ', a.pop())
print('a - ', a)
print('a - ', a.count(4))
ex = [8, 9]
a.extend(ex) // 끝부분에 리스트를 원소로 추가한다 (append를 쓰면 리스트를 삽입하게 된다)
print('a - ', a)
# 삭제 remove, pop, del
: remove는 원소값으로 뺀다, del은 인덱스로 뺀다, pop은 마지막 원소만 뺀다
# 반복문 활용
while a:
l = a.pop()
print(2 is l)
# 튜플 자료형(순서O, 중복O, 수정X,삭제X)
: 그러므로 변경하면 안 되는 중요 데이터를 쓸 때 사용한다
# 선언
a = () // 리스트는 {}
b = (1,) // 0번 인덱스에 하나만 들어가 있는 상태
c = (1, 2, 3, 4)
d = (10, 100, 'Pen', 'Cap', 'Plate')
e = (10, 100, ('Pen', 'Cap', 'Plate'))// 튜플 안에 튜플을 넣을 수 있다
// 수정, 삭제할 수 없다.
# 인덱싱
print('#=====#')
print('d - ', type(d), d)
print('d - ', d[1])
print('d - ', d[0] + d[1] + d[1])
print('d - ', d[-1])
print('e - ', e[-1][1])
print('e - ', e[-1][1][4])
print('e - ', list(e[-1][1]))
# 슬라이싱
print('#=====#')
print('d - ', d[0:3])
print('d - ', d[2:]) 다 나오는데 마지막, 나온다 ((a,b,c),)
print('e - ', e[2][1:3])
# 튜플 연산
print('#=====#')
print('c + d - ', c + d) // 모든 연소가 순서대로 나온다
print('c * 3 - ', c * 3) // 모든 연소가 순서대로 반복된다
# print("c[0] + 'hi' - ",c[0] + 'hi')
print("'hi' + c[0] - ", 'hi' + str(c[0])) //
# 튜플 함수
a = (5, 2, 3, 1, 4)
print('a - ', a)
print( 3 in a) // true
print('a - ', a.index(5)) // 인덱스 5번째가 없으니까 0
print('a - ', a.count(4)) // 이 튜플에서 4의 개수 : 1
(2) 딕셔너리, 집합
딕셔너리: 순서 X, 중복X, 수정O, 삭제O
key, value의 형태 (Json) -> MongoDB
선언
a = {'name' : 'Kim', 'Phone': '010-7777-7777', 'birth': 870214}
b = {0:'Hellp Python' }
c={'arr' : [1,2,3,4,5]}
// key로 숫자를 넣을 수도 있지만 대부분 의미가 있는 문자열 key를 사용한다
// 리스트, 튜플 등 모든 데이터타입을 value로 쓸 수 있다
#출력
print(a['name']) // key가 없으면 error
print(a.get('name')) // 없어도 None이라고 나온다
print(c['arr'][1:3])
#딕셔너리 추가
a['address'] = 'Seoul'
a['rank'] = [1, 3,4]
a['rank2'] = (1,2,3)
a[key] = value 식으로 추가할 수 있다
# keys, values, items
print(a.keys()) // key만 리스트 형태로 가져온다. 하지만 생긴거만 리스트여서 인덱싱 등은 할 수 없다
print(list(a.keys())) // 이게 진짜로 key만 리스트로 가져온다
temp = list(a.keys())
print(temp[1:3]) // 이때는 실제 리스트로 만들어서 인덱싱을 할 수 있다
a.values() // values만 리스트 형태. 실제 리스트는 아니다.
list(a.values)로 해줘야 리스트가 된다
a.items()로 하면 (key, value)의 형태의 튜플의 리스트가 된다
list(a.items)로 해줘야 리스트가 된다
key가 있는지 물어볼 수 있다
print( 1 in b)
print('name' in c)
#집합(Sets) (순서X, 중복X)
a = set()
b = set([1,2,3,4])
c = set([1,4,5,6,6])
print(c) // {1,4, 5, 6} 중복이 없어짐
t = tuple(b)
l = list(b)
로 형태를 바꿔줄 수 있다
교집합
s1.intersection(s2)
s1&s2
합집합
s1|s2
s1.union(s2)
차집합
s1-s2
s1.difference(s2)
추가와 제거
s3 = set([7,8,10,15])
s3.add(18) //[7,8,10,15,18]
s3.remove(15) // [7,8,10,18]
(3) 데이터 타입 - 퀴즈 및 풀이
section 4-5 파일 보기
2. 흐름 제어
(1) 조건문
if true:
무조건 실행
if false:
실행되지 않는다
if false:
여기는 실행되지 않는다
else:
여기는 실행
#관계 연산자
>, >=, <, <=, ==, !=
a= 10
b = 0
print(a ==b )// false
print(a != b)//true
#참 : "내용" , [내용], (내용), {내용}, 1
#거짓: "", [], (), {}, 0
ex.
city= ""
if city:
print("true")
else:
print("false")
// false
#논리 연산자
and 둘다 만족
or 하나만 만족
not 반대
#산술, 관계, 논리 연산자
# 산술> 관계>논리(순서)
print('ex1:' , 5+10 >0 and not 7+3 == 10 ) // 각각의 계산, not 마지막에 and
true and false
그러므로 false가 반환된다
#다중조건문
num = 90
if num >= 90:
print("num 등급 A", num)
elif num >= 80:
print("num 등급 B", num)
elif num >= 70
print("num 등급 C", num)
else:
print("꽝")
#중첩조건문
age = 27
height = 175
if age >= 20:
if height>= 170:
print("A지망 지원 가능")
elif height>= 160:
print("B지망 지원 가능")
else:
print("지원 불가")
else:
print("20세 이상 지원 가능")
// if 안에 if : 좀 더 세밀하게
(2) 반복문
파이썬 흐름제어(반복문)
v1 =1
while v1 < 11:
print("v1 is:", v1)
v1 += 1
// v1 is : 1 부터
v1 is : 10까지 나온다
for v2 in range(10): // 0~9
print("v2 is:", v2)
for v3 in range(1,11):
print("v3 is :", v3)
# 1~100합
sum1 = 0
cnt1 =1
while cnt <= 100:
sum1 += cnt1
cnt1 += 1
print('1~100:', sum1)
print('1~100:'. sum(range(1, 101, 2))) // 1부터 100까지 더하는데 2단위씩 건너뛰어라
2는 증감 단위
#시퀀스(순서가 있는) 자료형 반복
# 문자열, 리스트, 튜플, 집합, 사전
# iterable 리턴 함수 : range, reversed, enumerate, filter, map, zip 함수
names = ["1". "2", "3", "4" ,"5"]
for name in names:
print("You are:", name)
// name자리에 names의 원소가 하나씩
word = "dreams"
for s in word:
print ("Word :", s)
// 문자열에서 알파벳 하나씩 출력된다
my_info = {
"name": "Kim",
"age": 33,
"city": "Seoul"
}
#기본값은 키
for key in my_info:
print("my_info", key) // key만 반복된다
#값
for key in my_info.values():
print("my_info", key)// values만 하나씩 호출된다
#키
for key in my_info.keys():
print("my_info", key) // key가 호출된다
#키 and 값
for k,v in my_info.items():
print("my_info", k,v) // key와 value가 하나씩 호출된다
name = "KennRY"
for n in name:
if n.isupper():
print(m.lower())
else:
print(n.upper())
// 하나씩 출력되는데 소문자면 대문자로, 대문자면 소문자로
#break
내가 원하는 부분에서 break하고 반복문에서 나오도록 하는 신호
for문 중 멈추게 한다
number = [14, 2, 3, 4, 1, 33, 4,5,6,8,0]
// 33이 있는지 확인할 때 33을 발견한 뒤 바로 나가도록 하고 싶다
이때 break문을 사용하면 된다
for num in numbers:
if num == 33:
print()
break
else:
print("not found: 33!)
else: // for도 else구문이 있다
print("Not found 33......")
//만약 break가 수행되었으면 이미 나갔겠지만 break가 수행되지 않았으면 여기선 해당 값이 없다는 의미로 else문이 둘 다 나오게 된다
#continue
for문 중 스킵하게 한다
lt = ["1", 2, 5, True, 4.3, complex(4)]
for v in lt:
if type(v) is float:
continue // 아래 부분이 수행되지 않고 바로 다음 값으로 이동이 된다
print("타입: ", type (v))
// 그러므로 float형인 4.3이 들어가서 타입: float이 나오지 않는다.
(3) 퀴즈 및 풀이