You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#Tuples are another kind of sequence that function much like a list#they have elements which are indexed starting at 0x= ('Gleen', 'Sally', 'Joseph')
printx[2]
#Josephy= (1, 9, 2)
printy#(1, 9, 2)printmax(y)
#9foriteriny:
printiter#1#9#2# Tuples are "immutable"#Unlike a list, once you create a tuple, you cannot alter its contents- similar to a stringx= [9, 8, 7] #listx[2] =6printx#[9, 8, 6]y='ABC'#Stringy[2] ='D'#Traceback :# 'str' object does not support item assignmentz= (5, 4, 3) # Tuplesz[2] =0#Traceback :# 'str' object does not support item assignment# Things not to do with tuplesx= (3, 2, 1)
x.sort()
x.append(5)
x.reverse()
#Traceback :# 'tuple' object has no attribute 'sort', 'append', 'reverse'# A Tale of Two Sequencesl=list()
#dir(l)printdir(l)
#['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']t=tuple()
#dir(t) #what can we do with tupleprintdir(t)
#['count', 'index']# Tuples are more efficient# So we prefer tuples over lists when we are making "temporary variables"#Tuples and Assignment#We can also put a tuple on the left hand side of an assignment statement#We can even omit the parenthesis
(x, y) = (4, 'fred')
printy#freda, b= (99, 98)
printa#99# Tuples and Dictionaries# The items() method in dictionaries returns a list of (key, value) tuplesd=dict()
d['csev'] =2d['cwen'] =4for (k,v) ind.items():
printk, vtups=d.items()
printtups# Tuples are Comparable# The comparison operators work with tuples and other sequences# If the first item is equal, Python goes on to the next element, and so on
(0, 1, 2) < (5, 1, 2)
#True
(0, 1, 2000000) < (0, 3, 4)
#True
('Jones', 'Sally') < ('Jones', 'Fred')
#False
('Jones', 'Sally') > ('Adams', 'Sam')
#True# Sorting Lists of Tuples# First we sort the dictionary by the key using the items() methodd= {'a':10, 'b':1, 'c':22}
t=d.items()
tprintt#[('a', 10), ('c', 22), ('b', 1)]t.sort()
tprintt#[('a', 10), ('b', 1), ('c', 22)]# Using sorted() # We can do this even more directly using the built-in function sorted # that takes a sequence as a parameter and returns a sorted sequenced= {'a':10, 'b':1, 'c':22}
d.items()
printd.items()
#[('a', 10), ('c', 22), ('b', 1)]t=sorted(d.items())
printt#[('a', 10), ('b', 1), ('c', 22)]fork, vinsorted(d.items()):
printk, v#a 10#b 1#c 22# Sort by values instead of key# If we could construct a list of tuples of the form (value,key) we could sort by value# We do this with a for loop that creates a list of tuplesc= {'a':10, 'b':1, 'c':22}
tmp=list()
fork, vinc.items():
tmp.append( (v, k) )#make a two_tuple with values from the v and K variable#and append a listprinttmp#[(10, 'a'), (22, 'c'), (1, 'b')]#each of the tuples now has the value first and the key second#they a in a listtmp.sort(reverse=True)# List is mutable printtmp#[(22, 'c'), (10, 'a'), (1, 'b')]#a list in new order# Top 10 most common wordsfhand=open('romeo.txt')#open a filecounts=dict ()#create a empty counts dictionaryforlineinfhand:#write a for loop that reads each line for line in fhandwords=line.split()#split each line into words, based on the splaceforwordinwords:#loop each word in each linecounts[word] =counts.get(word, 0) +1#If the word key exists, give me back the value that's in that, otherwise give me zero#create the new entries and update old entries#we are going to have counts with keyword word-count pairslst=list()
forkey, valincounts.items():
lst.append((val, key)) #create temporary list of tuples that are val, comma, keylst.sort(reverse=Ture) #the biggest value will near the topforval, keyinlst[:10]: #first 10 itemsprintkey, val# Even Shorter Version(adv)c= {'a':10, 'b':1, 'c':22} #a dictionaryprintsorted([(v,k) fork,vinc.items()])
#[(1, 'b'), (10, 'a'), (22,'c')]#List comprehension creates a dynamic list. In this case, #we make a list of reversed tuples and then sort it#http://wiki.python.org/moin/HowTo/Sorting#[(v,k) for k,v in c.items()] construct dynamically a list of tuples v, comma, k#loop through the items with k and v taking on the successive values#(v,k) is creating a reversed list where value and key are the order of the items in each tuple#pass it to sort, this is a function call #print out its ascending order of the value
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: