This repository was archived by the owner on Mar 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_07.py
More file actions
280 lines (186 loc) · 6.69 KB
/
Day_07.py
File metadata and controls
280 lines (186 loc) · 6.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
## 튜플
tuple1 = (10, 20, 30)
print(tuple1)
tuple2 = 10, 20, 30
print(tuple2)
# ------------------------------ #
# 튜플은 읽기 전용이므로 값을 수정할 수 없음
# tuple1.append(40) # 'tuple' 객체엔 'append' 속성 없음
# tuple1[0] = 40 # 'tuple' 객체는 item 배정을 지원하지 않음
# del(tuple1[0]) # 'tuple' 객체는 item 삭제를 지원하지 않음
# del() 함수를 사용하여 아예 삭제할 수 있음
del(tuple1)
del(tuple2)
# ------------------------------ #
# 튜플 접근
tuple1 = (10, 20, 30, 40)
print(tuple1[0])
print(tuple1[0] + tuple1[1] + tuple1[2])
print(tuple1[1:3])
print(tuple1[1:])
print(tuple1[:3])
# ------------------------------ #
# 튜플 연산
tuple2 = ('A', 'B')
print(tuple1 + tuple2)
print(tuple2 * 3)
# ------------------------------ #
# 튜플 값 수정을 위한 <튜플 - 리스트 - 튜플> 변환
myTuple = (10, 20, 30)
myList = list(myTuple)
myList.append(40)
myTuple = tuple(myList)
print(myTuple)
# ------------------------------ #
# 튜플을 사용하는 이유:
# 값 보호
# 리스트 대비 적은 메모리, 빠른 속도
# 튜플 특징:
# 서로 다른 데이터형 함께 수용 가능
# 튜플 속 튜플 입력 (중첩) 가능
# 리스트에서 가능한 연산 가능
# 인덱싱할 때 대괄호 사용 (리스트와 동일)
# 값 조작은 불가하나 접근 방식은 리스트와 유사
# ------------------------------ #
## 딕셔너리
Dict = {'apple': '사과', 'banana': '바나나'}
print(Dict['apple'])
# ------------------------------ #
student1 = {'학번': 1000, '이름': '홍길동', '학과': '컴퓨터학과'}
print(student1)
# 추가
student1['연락처'] = '010-1111-2222'
print(student1)
# 수정
student1['학과'] = '파이썬학과'
print(student1)
# 삭제
del(student1['학과'])
print(student1)
# 키로 값에 접근
print(student1['학번'])
print(student1['이름'])
print(student1['연락처'])
# get()으로 값에 접근
print(student1.get('이름'))
# ------------------------------ #
# key()로 모든 키 반환
print(student1.keys())
# 모든 키를 리스트로 변환
print(list(student1.keys()))
# values()로 모든 값 반환
print(student1.values())
# ------------------------------ #
# items()로 튜플 형태로 활용
print(student1.items())
# in으로 해당 키가 딕셔너리에 존재하는지 확인
print('이름' in student1) # True
print('주소' in student1) # False
# ------------------------------ #
# for 문으로 모든 딕셔너리 값 출력
singer = {}
singer['이름'] = '트와이스'
singer['구성원 수'] = 9
singer['데뷔'] = '서바이벌 식스틴'
singer['대표곡'] = 'SIGNAL'
for k in singer.keys():
print('%s → %s' % (k, singer[k]))
# ------------------------------ #
# 딕셔너리 정렬 (가능하다는 것만 참고)
import operator
trainDict, trainList = {}, []
trainDict = {'Thomas': '토마스', 'Edward': '에드워드', 'Henry': '헨리', 'Gordon': '고든', 'James': '제임스'}
trainList = sorted(trainDict.items(), key = operator.itemgetter(0))
print(trainList)
# ------------------------------ #
# 예제
foods = {
"떡볶이": "오뎅",
"짜장면": "단무지",
"라면": "김치",
"피자": "피클",
"맥주": "땅콩",
"치킨": "치킨무",
"삼겹살": "상추"
}
# while True:
# myFood = input(str(list(foods.keys())) + " 중 좋아하는 음식은? ")
# if myFood in foods:
# print("%s의 궁합 음식은 %s입니다." % (myFood, foods[myFood]))
# elif myFood == "끝":
# break
# else:
# print("그런 음식은 없습니다. 보기를 확인해 보세요.")
# ------------------------------ #
## 세트, 키만 모아놓은 딕셔너리의 특수 형태:
# 딕셔너리 키는 중복하여 넣을 수 없으므로 하나씩만 기록됨
mySet = {1, 2, 3, 3, 3, 4}
print(mySet)
salesList = ['바나나', '바나나', '사과', '바나나', '바나나']
print(set(salesList))
# ------------------------------ #
# 세트 간의 교집합, 합집합, 차집합, 대칭 차집합
mySet1 = {1, 2, 3, 4, 5}
mySet2 = {4, 5, 6, 7}
print(mySet1 & mySet2)
print(mySet1 | mySet2)
print(mySet1 - mySet2)
print(mySet1 ^ mySet2)
print(mySet1.intersection(mySet2))
print(mySet1.union(mySet2))
print(mySet1.difference(mySet2))
print(mySet1.symmetric_difference(mySet2))
# ------------------------------ #
## 리스트, 튜플, 딕셔너리 심화
# zip()으로 동시에 여러 리스트 접근
mainDish = ['떡볶이', '짜장면', '라면', '피자', '맥주', '치킨', '삼겹살']
sideDish = ['오뎅', '단무지', '김치']
for mainDish, sideDish in zip(mainDish, sideDish):
print(mainDish, ' → ', sideDish)
# ------------------------------ #
# zip()으로 두 리스트를 튜플이나 딕셔너리로 짝지음
mainDish = ['떡볶이', '짜장면', '라면', '피자', '맥주', '치킨', '삼겹살']
sideDish = ['오뎅', '단무지', '김치']
tupList = list(zip(mainDish, sideDish))
dic = dict(zip(mainDish, sideDish))
print(tupList)
print(dic)
# ------------------------------ #
# 리스트의 얕은 복사와 깊은 복사
# 얕은 복사
oldList = ['짜장면', '탕수육', '군만두']
newList = oldList
print(newList)
oldList[0] = '짬뽕'
oldList.append('깐풍기')
print(newList)
# 깊은 복사
oldList = ['짜장면', '탕수육', '군만두']
newList = oldList[:]
print(newList)
oldList[0] = '짬뽕'
oldList.append('깐풍기')
print(newList)
# ------------------------------ #
# 스택(Stack): 한 쪽 끝이 막혀 먼저 들어간 것이 나중에 나오는 (= 가장 나중에 들어간 것이 가장 먼저 나오는 (Last-In-First-Out)) 형태의 자료구조
# Top: 스택에 들어있는 자료 중 가장 마지막 자료의 바로 다음 위치
# Push: 자료를 넣는 것
# Pop: 자료를 빼는 것
# 스택의 예: 웹 브라우저 뒤로가기, 실행 취소 (Ctrl + Z)
# 리스트로 스택 구현
parking = []
top = 0
parking.append('자동차 A')
top += 1
parking.append('자동차 B')
top += 1
parking.append('자동차 C')
top += 1
top -= 1
outCar = parking.pop()
print(outCar)
top -= 1
outCar = parking.pop()
print(outCar)
# 큐(Queue): 파이프같은 모양으로 양쪽이 뚫린, 한 쪽으로 들어가면 다른 한 쪽으로 나오는 (= 가장 먼저 들어간 것이 가장 먼저 나오는 (First-In-First-Out)) 형태의 자료구조
# 큐의 예: 작업 예약, 프린터 스케줄, 콜센터 대기