Tuples are another king of sequence that functions much like a list - they have elements which are indexed starting at 0
>>> x = ('Glenn', 'Sally', 'Joseph')
>>> print(x[2])
Joseph
>>> y = (1, 9, 2)
>>> print(y)
(1, 9, 2)
>>> print(max(y))
9
Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string
>>> l = list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> t = tuple()
>>> dir(t)
['count', 'index']
>>> (x, y) = (4, 'fred')
>>> print(y)
fred
>>> (a, b) = (99, 98)
>>> print(a)
99
The items() method in dictionaries returns a list of (key, value) tuples
>>> 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)])
The comparison operators work with
tuples and other sequences. If the first item is equl, Python goes on to the next element, and so on, until it finds elements that differ.
(0, 1, 2) < (5, 1, 2)
# True 값을 가집니다.
(0, 1, 2000000) < (0, 3, 4)
# True 값을 가집니다.
( 'Jones', 'Sally' ) < ('Jones', 'Sam')
# True 값을 가집니다.
( 'Jones', 'Sally') > ('Adams', 'Sam')
# True 값을 가집니다.
>>> d = {'a':10, 'b':1, 'c':22}
>>> d.items()
dict_items([('a', 10), ('c', 22), ('b', 1)])
>>> sorted(d.items())
[('a', 10), ('b', 1), ('c', 22)]
We can do this even more directly using the built-in function sorted that takes a sequence as a parameter and returns a sorted sequence
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = sorted(d.items())
>>> t
[('a', 10), ('b', 1), ('c', 22)]
>>> for k, v in sorted(d.items()):
print(k, v)
...
...
a 10
b 1
c 22
>>> 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')]
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)
List comprehension creates a dynamic list. In this case, we make a list of reversed tuples and then sort it.
c = {'a':10, 'b':1, 'c':22}
print( sorted( [ (v,k) for k,v in c.items() ] ) )
# [(1, 'b'), (10, 'a'), (22, 'c')]