01.list
'''
list 특징
- 1차원 배열 구조
형식) 변수 = [값1, 값2]
- 다양한 자료형 저장 가능
- index 사용=순서 존재
형식) 변수[n]
- 값 수정(추가,수정,삭제,삽입)
'''
# 1. 단일 list
lst = [1,2,3,4,5]
print(lst) # [1, 2, 3, 4, 5]
lst = list(range(1,6))
print(lst) # [1, 2, 3, 4, 5]
for i in lst :
print(lst[i-1:]) # [start:]
'''
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
'''
for i in lst :
print(lst[:i]) # [:end]
'''
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
'''
# 마지막 5개 자료
x = list(range(1,1001))
print(x[:5]) # 첫 5개
print(x[-5:]) # 마지막 5개
'''
[1, 2, 3, 4, 5]
[996, 997, 998, 999, 1000]
'''
# 홀수/짝수 단위 index
print(x[::2]) # [1, 3, 5, 7, 9,
print(x[1::2]) # [2, 4, 6, 8, 10,
# 2. 중첩 list
'''
변수 = [ [] ]
'''
a = ['a', 'b', 'c']
b = [10, 20, a, True, "string"]
print(b)
# [10, 20, ['a', 'b', 'c'], True, 'string']
# 중첩 list index
print(b[2]) # a - ['a', 'b', 'c']
print(b[2][2]) # c
# 3. 추가,수정,삭제,삽입
'''
Object.member()
num.appen(),remove(),insert()
'''
num = ['one', 'two', 'three', 'four']
print(type(num)) # <class 'list'>
# 1) 추가
num.append(5) # 마지막 추가
print(num)
# ['one', 'two', 'three', 'four', 5]
# 2) 수정[index 이용]
num[4] = 'five'
print(num)
# ['one', 'two', 'three', 'four', 'five']
# 3) 삭제
num.remove('two')
print(num)
# ['one', 'three', 'four', 'five']
# 4) 삽입
num.insert(0, 'zero')
print(num)
# ['zero', 'one', 'three', 'four', 'five']
# 4. list 연산
# 1) list 결합
x = [1,2,3,4]
y = [1.5, 2.5]
z = x + y # new object = 결합
print('z=', z) # z= [1, 2, 3, 4, 1.5, 2.5]
# 2) list 확장
x.extend(y)
print('x=', x) # x= [1, 2, 3, 4, 1.5, 2.5] : 단일 list
# 3) list 추가
x.append(y)
print('x=', x)
# x= [1, 2, 3, 4, 1.5, 2.5, [1.5, 2.5]] : 중첩 list
# 4) 곱셈
lst = [1,2,3,4]
result = lst * 2
print(result) # [1, 2, 3, 4, 1, 2, 3, 4]
# 각 원소 연산
for i in range(len(lst)) : # 0~3
print(lst[i] * 2)
'''
2
4
6
8
'''
'''
list : 선형대수 연산 불가
-> numpy 형 변환 필요
'''
02.list2
'''
1. 성적처리
2. list + for
'''
# 1. 성적처리
hong = [95, 85, 63]
lee = [95, 85, 90]
kang = [99, 85, 90]
# 중첩 list
student = [hong, lee, kang] # [[],[],[]]
print('국어\t영어\t수학')
print('='*20)
for score in student : # 학생수
print("%d\t%d\t%d"%(score[0], score[1], score[2]))
print('='*20)
print('국어\t영어\t수학')
print('='*20)
for score in student : # 학생수
print("{} {} {}".format(score[0],score[1],score[2]))
print('='*20)
# 2. list + for
'''
형식1)
변수 = [ 실행문 for 변수 in 열거형객체 ]
- 실행순서 : 1. for > 2. 실행문 > 3. 변수 저장
'''
# 영문자/숫자 -> ASCII(기계어)
string = "ab#c123d%f$z"
help(ord)
asc = [ord(ch) for ch in string] # 'a' -> 97
print('ASCII=', asc)
# ASCII= [97, 98, 99, 49, 50, 51, 100, 102, 122]
# dummy 변수 만들기 : 홀수=0, 짝수=1
x = list(range(1,101))
dummy = [1 if i%2 == 0 else 0 for i in x ]
print(dummy) # [0, 1, 0, 1, ...]
# 문) string변수를 대상으로 영문자->"영문",숫자->"숫자" 더미 생성
# 힌트: a~z(97~122)
dummy2 = ["영문" if ord(ch)>=97 and ord(ch)<=122 else "숫자"
for ch in string]
print(dummy2) # "abc123dfz"
# ['영문', '영문', '영문', '숫자', '숫자', '숫자', '영문', '영문', '영문']
'''
형식2)
변수 = [ 실행문 for 변수 in 열거형객체 if 조건식]
- 실행순서 : 1. for > 2. if > [3. 실행문] > 4. 변수 저장
'''
num = list(range(1,11))
print(num) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num2 = [n for n in num if n%2 == 0]
print(num2) # [2, 4, 6, 8, 10]
# 문2) string변수를 대상으로 영문자만 추출하기
alpha = [ch for ch in string if ord(ch)>=97 and ord(ch)<=122]
print(alpha)
# ['a', 'b', 'c', 'd', 'f', 'z']
string2 = ''.join(alpha) # '구분자'.join(열거형객체)
print(string2) # abcdfz
'''
"ab#c123d%f$z" -> 전처리 -> abcdfz
'''
# 3. list + 이중 for
'''
변수 = [실행문 outer for inner for ]
'''
colors = ['Blue', 'Red']
sizes = ['S','M','L']
choose = [[c, s] for c in colors for s in sizes ]
print(choose)
# [['Blue', 'S'], ['Blue', 'M'], ['Blue', 'L'], ['Red', 'S'], ['Red', 'M'], ['Red', 'L']]
03.tuple
'''
tuple 특징
- list 자료구조 유사 : index=0
형식) 변수 = (값1, 값2)
- 순서 존재
- 읽기 전용(고속 처리) : 수정 불가
'''
t1 = 10 # 스칼라 변수
t2 = (10,) # tuple 변수
print(t1, t2) # 10 (10,)
t3 = (1,2,3,4)
print(t3, type(t3))
# (1, 2, 3, 4) <class 'tuple'>
# index 사용(순서 존재)
print(t3[:2]) # (1, 2)
print(t3[-2:]) # (3, 4)
# 수정 불가
# t3[0] = 'one' Error 발생
# tuple packing/unpacking
pinfo = [('홍길동', 35, (170,65)),
('이순신', 45, (180,95)),
('유관순', 25, (165,45))] # (키,몸무게)
for name,age,(h,w) in pinfo : # (name,age(h,w))
if w > 60 :
print(name, age, (h, w))
'''
홍길동 35 (170, 65)
이순신 45 (180, 95)
'''
#####################
### tuple 반환 함수
#####################
# 1. zip()
name = ['홍길동', '이순신', '유관순']
age = [35,45,25]
#help(zip)
person = list(zip(name, age))
print(person) # object info
# [('홍길동', 35), ('이순신', 45), ('유관순', 25)]
print(list(range(5))) # [0, 1, 2, 3, 4]
sel = [1,2] # 선택자 : 2명
person2 = list(zip(sel, name, age))
print(person2)
# [(1, '홍길동', 35), (2, '이순신', 45)]
sel = [1,2,3] # 선택자 : 3명
person3 = list(zip(sel, name, age))
print(person3)
# [(1, '홍길동', 35), (2, '이순신', 45), (3, '유관순', 25)]
# 2. url 파싱
from urllib.parse import urlparse, urlunparse
# from package.module import class or function
#help(urlparse)
url = "http://www.naver.com/index.html?id=hong"
url_info = urlparse(url)
print(url_info)
# ParseResult(scheme='http', netloc='www.naver.com', path='/index.html', params='', query='id=hong', fragment='')
print('domain name :', url_info.netloc)
# domain name : www.naver.com
url2 = urlunparse(url_info)
print(url2) # http://www.naver.com/index.html?id=hong
04.set
'''
set 특징
- 순서 없음(index 사용 불가)
- 중복 불가
형식) 변수 = {값1, 값2,...}
- 집합 개념
'''
s = {1,3,5} # 중복 불가
print(s) # {1, 3, 5}
# for + set 이용
for i in s :
print(i, end = ' ') # 1 3 5
print()
# 집합 처리
s2 = {3, 6}
print(s.union(s2)) # 합집합 - {1, 3, 5, 6}
print(s.difference(s2)) # 차집합 - {1, 5}
print(s.intersection(s2)) # 교집합 - {3}
# 중복 데이터 처리
gender = ['남', '여', '남', '여']
sgender = set(gender) # list -> set
print(sgender) # {'여', '남'}
#print(sgender[1]) # indexing 사용 불가
# set -> list
gender = list(sgender)
print(gender) # ['여', '남']
print(gender[1]) # 남
# 원소 추가, 삭제, 수정(x)
s3 = {1,3,5,7}
print(type(s3)) # <class 'set'>
s3.add(9) # 원소 추가
print(s3) # {1, 3, 5, 7, 9}
s3.discard(3) # 원소 삭제
print(s3) # {1, 5, 7, 9}
05.dict
'''
dict 특징
- set과 유사함
형식) 변수 = {key:값1, key:값2, ...}
- 순서 없음(index 사용 불가) - random
- key을 통해서 값 참조
- key 중복 불가(값 중복 가능)
'''
# dict 생성 방법1
dic = dict(key1=100, key2=200, key3 = 300)
print(dic, type(dic))
# {'key1': 100, 'key2': 200, 'key3': 300} <class 'dict'>
# 방법2
dic2 = {'name':'홍길동', 'age':35, 'addr':'서울시'}
print(dic2) # {'name': '홍길동', 'age': 35, 'addr': '서울시'}
# key 이용 참조
age = dic2['age']
print('age :', age) # age : 35
# dict에 해당 키 유무 검사
print('age' in dic2) # True
print('address' in dic2) # False
# 원소 수정, 삭제, 추가
person = dic2
print(person) # {'name': '홍길동', 'age': 35, 'addr': '서울시'}
# 나이 수정
person['age'] = 45
print(person)
# 급여 추가
person['pay'] = 350
print(person)
# {'name': '홍길동', 'age': 45, 'addr': '서울시', 'pay': 350}
# 주소 삭제
del person['addr']
print(person)
{'name': '홍길동', 'age': 45, 'pay': 350}
# for + dict
'''
for 변수 in 열거형객체(list,tuple,set,dict)
'''
for key in person : # person.keys()
print(key)
'''
name
age
pay
'''
for value in person.values() :
print(value)
'''
홍길동
45
350
'''
for item in person.items() : # (key,value)
print(item)
'''
('name', '홍길동')
('age', 45)
('pay', 350)
'''
# key -> value 리턴
name = person['name'] # index 형식
print(name)
name = person.get('name') # get()형식
print(name)
# {key : [value1, value2]}
movie = {'광해' : [9.24, 1200],
'공작' : [7.8, 560],
'관상' : [8.02, 900]}
print(movie)
# {'광해': [9.24, 1200], '공작': [7.8, 560], '관상': [8.02, 900]}
for m in movie.items() :
print(m)
for title, point in movie.items() :
print(title, point)
'''
(제목, [평점, 관객수])
('광해', [9.24, 1200])
('공작', [7.8, 560])
('관상', [8.02, 900])
title point
광해 [9.24, 1200]
공작 [7.8, 560]
관상 [8.02, 900]
'''
# 평점이 8이상 영화 출력하기
for k, v in movie.items() :
# k=title, v=[평점, 관객수]
if v[0] >= 8.0 :
print(k)
'''
광해
관상
'''
# 문) 평점이 8이상 영화의 누적 관객수 출력하기
'''
광해
관상
누적 관객수 = 2,100
'''
tot = 0 # 초기화
for k, v in movie.items() :
# k=title, v=[평점, 관객수]
if v[0] >= 8.0 :
print(k) # 영화 제목 출력
tot += v[1] # 관객수 누적
print('누적 관객수=', format(tot, '3,d'))
# 단어 빈도수 구하기
word_set = ['test', 'set', 'list', 'test', 'list']
word_count = {} # 빈 set
for word in word_set : # 'test'
# key = value
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# {'test': 2, 'set': 1, 'list': 2}