리스트와 비슷한 컬렉션, 튜플
튜플은 리스트와 굉장히 비슷합니다.
리스트와 같이 순서가 있어서 인덱스로 접근이 가능하고 최대값도 찾을 수 있습니다.
x = ('Glenn', 'Sally', 'Joseph')
print(x[2])
#Joseph
y=(1,9,2)
print(y)
#(1,9,2)
print(max(y))
#9
for iter in y:
print(iter)
#1
#9
#2
변경 불가능한 속성
하지만 리스트와는 달리 튜플은 값을 변경할 수 없다는 특징이 있습니다.
이러한 특성으로 인해 튜플은 리스트보다 훨씬 더 효율적으로 동작합니다. 용량도 적게 차지하고 접근도 빠릅니다.
x=[9,8,7]
x[2] = 6
print(x)
#[9,8,6]
x=(9,8,7)
x[2] = 6
#TypeError
리스트와 튜플의 내장함수
l = list()
dir(l)
#['append','count','extend','index','insert','pop','remove','reverse','sort']
t = tuple()
dir(t)
#['count', 'index']
튜플의 장점
1) 임시 변수로 활용
(x, y) = (4, 'fred')
print(y)
#fred
(a,b) = (99,98)
print(a)
#99
def t():
return(10,20)
x,y = t()
print(x,y)
#10 20
x,y = 1,10
print(x,y)
#1 10
x,y = y,x
print(x,y)
#10 1
2) 딕셔너리를 처리하는데 활용
d = dict()
d['csev'] = 2
d['cwen'] = 4
for(k,v) in d.items():
print(k,v)
#csev 2
#cwen 4
tups = d.items()
print(tups)
#dict_items([('csev', 2), ('cwen', 4)])
3) 가장 왼쪽 값부터 여러 값을 비교
(0,1,2)<(5,1,2)
#True 값을 가집니다.
(0,1,2000000)<(0,3,4)
#True 값을 가집니다.
('Jones', 'Sally')<('Jones', 'Sam')
#True 값을 가집니다.
('Jones', 'Sally')>('Adams', 'Sam')
#True 값을 가집니다.
튜플의 특성을 활용해 딕셔너리 정렬하기
1) 키를 기준으로 정렬하기
- 딕셔너리에서 items 메소드를 실행해 튜플로 이루어진 리스트 형태로 만든다.
- 이 리스트를 sorted 함수로 정렬한다. 그러면 각각의 튜플의 왼쪽 값, 키를 기준으로 정렬이 된다.
d = {'b':1, 'a':10, 'c':22}
d.items()
#dict_items([('b',1),('a',10),('c',22)])
sorted(d.items())
#[('a',10),('b',1),('c',22)]
for k,v in sorted(d.items()):
print(k,v)
#a 10
#b 1
#c 22
2) 값을 기준으로 정렬하기
- 딕셔너리에서 items 메소드를 실행
- 튜플을 활용해 키와 값을 분리
- 키와 값의 위치를 바꾼 리스트를 생성
- 생성한 리스트를 정렬
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k,v in c.items():
tmp.append((v,k))
print(tmp)
#[(10,'a'),(1,'b'),(22,'c')]
tmp = sorted(tmp)
print(tmp)
#[(1,'b'),(10,'a'),(22,'c')]
tmp = sorted(tmp, reverse=True)
print(tmp)
#[(22,'c'),(10,'a'),(1,'b')]
가장 많이 등장한 단어 Top 10 출력하기
fhand = open('romeo.txt')
counts = {}
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word,0)+1
lst = []
for key, val in counts.items():
newtup = (val, key)
lst.append(newtup)
lst = sorted(lst, reverse=True)
for val, key in lst[:10]:
print(key,val)
리스트 컴프리헨션
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k,v in c.items():
tmp.append((v,k))
print(tmp)
#[(10,'a'),(1,'b'),(22,'c')]
tmp = sorted(tmp)
print(tmp)
#[(1,'b'),(10,'a'),(22,'c')]
c = {'a':10, 'b':1, 'c':22}
print(sorted([(v,k) for k,v in c.items()]))
#[(1,'b'),(10,'a'),(22,'c')]
tmp = sorted(tmp, reverse=True)
print(tmp)
#[(22,'c'),(10,'a'),(1,'b')]
실습 문제
fname = input('Enter File: ')
if len(fname) < 1 : fname = 'clown.txt'
hand = open(fname)
di = dict()
for lin in hand:
lin = lin.rstrip()
wds = lin.split()
for w in wds:
di[w] = di.get(w,0) + 1
#print(di)
tmp = list()
for k,v in di.items() :
#print(k,v)
newt = (v,k)
tmp.append(newt)
#print('Flipped',tmp)
tmp = sorted(tmp, reverse=True)
#print('Sorted',tmp[:5])
for v,k in tmp[:5]:
print(k,v)
'마케팅 > 데이터분석(파이썬)' 카테고리의 다른 글
(파이썬/python) 모두를 위한 프로그래밍 : 파이썬 챕터 12 / HTTP (0) | 2021.11.24 |
---|---|
(파이썬/python) 모두를 위한 프로그래밍 : 파이썬 챕터 11 / 정규식 (0) | 2021.11.22 |
(파이썬/python) 모두를 위한 프로그래밍 : 파이썬 챕터 9 / 딕셔너리 (0) | 2021.11.18 |
(파이썬/python) 모두를 위한 프로그래밍 : 파이썬 챕터 8 / 리스트 (0) | 2021.11.17 |
(파이썬/python) 모두를 위한 프로그래밍 : 파이썬 챕터 7 / 파일 (0) | 2021.11.17 |