딕셔너리형 사용법
dictionary는 key와 value의 쌍
#dictionary 사용법
name_to_age = {"Jenny": 20, "Ella":31}
#name_to_age = {} 처럼 빈 dictionary로 선언가능
name_to_age["John"] = 26
name_to_age["Tom"] = 29
#마음대로 추가 가능
print(name_to_age["Jenny"])
print(name_to_age["John"])
print(name_to_age["Tom"])
name_to_age["Jenny"] = 21
#수정 가능
print(name_to_age["Jenny"])
print(name_to_age.get("Jenny"))
#두가지 접근법
print(name_to_age.keys())#key(이름)들만 표시
print(name_to_age.values())#value(나이)들만 표시
print(name_to_age.items())#key value 동시표시
for name in name_to_age.keys():
print(name, name_to_age[name])
#for문 등에서 key들을 순회 가능, name_to_age[key]으로 접근가능
#items를 순회하면 key, value 동시 순회 for key, value in name_to_age.items
for i, name in enumerate(name_to_age.keys()):
print(i, name, name_to_age[name])
#enumerate 는 접근만 아니라 인덱스매김(몇번째) i가 0,1... 인덱스 받음
print("Andrew" in name_to_age)
print("Ella" in name_to_age)
#dictionary 내 유무 true false 반환
20
26
29
21
21
dict_keys(['Jenny', 'Ella', 'John', 'Tom'])
dict_values([21, 31, 26, 29])
dict_items([('Jenny', 21), ('Ella', 31), ('John', 26), ('Tom', 29)])
Jenny 21
Ella 31
John 26
Tom 29
0 Jenny 21
1 Ella 31
2 John 26
3 Tom 29
False
True
집합 사용법
중복제거 집합 생성
#집합
s1 = set("Hello")
print(s1)
s2 = set([1, 1, 2, 2, 3, 4, 5])
print(s2)
{'l', 'e', 'o', 'H'}
{1, 2, 3, 4, 5}
연습문제1
student2score = { "Darius": 100, "Dr. Mundo": 80, "Morgana": 60, "Sivir": 75, "Yummi": 20, "Viktor": 97 }
def get_special_students(student2score):
"""
특별반 학생의 리스트를 리턴하는 함수 특별반은 점수가 80점 이상이어야 들어갈 수 있다.
:param student2score:
:return special_students:
"""
special_students = []
return special_students
student2score = {
"Darius": 100,
"Dr. Mundo": 80,
"Morgana": 60,
"Sivir": 75,
"Yummi": 20,
"Viktor": 97
}
def get_special_students(student2score):
special_students = []
for name in student2score.keys():
if student2score[name] >= 80:
special_students.append(name)
return special_students
print(get_special_students(student2score))
['Darius', 'Dr. Mundo', 'Viktor']
연습문제2
text = "Apple is fruit. Orange is also fruit. Tomato is fruit?"
def word_index_count(text):
"""
텍스트 안에 단어에 id를 부여하고 각 단어의 빈도수를 세어 각각의 텍스트에 해당하는 id를 저장하는 딕셔너리와 각 각의 단어 id에 해당하는 빈도수를 저장하는 딕셔너리 리턴 텍스트 안에 특수 기호는 제거해야한다 모든 단어는 소문 자 형태로 관리한다
"""
word_id = {}
id_frequency = {}
return word_id, id_frequency
print(word_index_count(text))
import re
text = "Apple is fruit. Orange is also fruit. Tomato is fruit?"
def word_index_count(text):
cleaned_text = re.sub('\W+', ' ', text).lower().split()
#\W는 숫자와 문자가 아닌것
words_list = set(cleaned_text)
word_id = {}
for i, word in enumerate(words_list):
word_id[i] = word
id_frequency = {}
for word in words_list:
id_frequency[word] = cleaned_text.count(word)
return word_id, id_frequency
print(word_index_count(text))
({0: 'also', 1: 'tomato', 2: 'orange', 3: 'fruit', 4: 'is', 5: 'apple'}, {'also': 1, 'tomato': 1, 'orange': 1, 'fruit': 3, 'is': 3, 'apple': 1})
연습문제3
별트리
*
***
*****
*******
*********
n = 5
for i in range(1, n+1):
print(' '*(n-i) + '*'*(i*2-1))
*
***
*****
*******
*********
'파이썬 딥러닝 ai 스쿨 기초 > lecture02' 카테고리의 다른 글
lecture02 2교시 인공지능 텐서플로우 실습 필기체 인식기1 (0) | 2021.03.22 |
---|---|
lecture02 1교시 개념정리 (0) | 2021.03.15 |