Programming for everybody (Python) - 10.Tuples
10. Tuples
Tuples은 세번째 Collection! List와 Dictionary에 이어서. List랑 비슷함. 순서가 변하지 않고, 0번부터 시작하지.
But, Tuples are “immutable”
list와 다르게 tuple 은 한 번 생성하면 수정할 수 없어. string 같아1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
169, 8, 7] x = [
2] = 6 x[
print (x)
[9, 8, 6]
'ABC' y =
2] = 'D' y[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
5, 4, 3) z = (
2] = 0 x[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Thing not to do with tuples
sort()
append()
reverse()
Traceback을 보게 될 것이야
A Tale of Two Sequences
1 | t = tuple() |
Tuples are more efficient
Python은 tuple을 수정 불가능하게 만들기 때문에 메모리를 사용하는 데 있어 list보다 더 간단하고 더 효과적인 performance 를 낸다. 그래서 우리가 만약에 임시 변수로 뭔가를 사용할 일이 있다면 list보다는 tuple을 쓰는 것이 좋으다.
Tuples and Assignment
오 우리는 tuple을 할당문의 왼쪽에도 넣을 수 있어!1
2
3
4
5
64, 'fred') (x, y) = (
print (y)
fred
99, 98) (a, b) = (
print (a)
99
Tuples and Dictionaries
dictionary의 items()
메소드는 (key, value) tuple의 list를 return
Tuples are Comparable
비교 연산자는 tuples이나 다른 sequence에도 먹힘. 만약 첫번째 item이 같으면 Python은 다음 항목으로 넘어감. 다른 애를 찾을 때까지!1
2
3
4
5
6
7
80, 1, 2) < (5, 1, 2) (
True
0, 1, 20000) < (0, 3, 4) (
True
'Jones', 'Sally') < ('Jones', 'Fred') (
False
'Jones', 'Sally') > ('Adams', 'Sam') (
True
Sorting Lists of Tuples
우리는 sorting된 dictionary를 원할 때, tuples의 list를 sorting하는 방식을 쓸 수 있어!1
2
3
4
5
6
7'a':10, 'b':1, 'c':22} d = {
t = d.items()
t
[('a', 10), ('b', 1), ('c', 22)]
t.sort()
t
[('a', 10), ('b', 1), ('c', 22)]
Using sorted()
위와 같은 동작을 그냥 sorted 함수를 이용해서 할 수도 있음
Sort by values instead of key
1 | tmp.sort(reverse=True) |
10 Most Common Words
1 | counts = dict have a count of words |
Even Shorter Version (adv)
1 | c = {'a':10, 'b':1, 'c':22} |