Python
>Datastrukturer
Python datastrukturer
List
Programmet setter opp en enkel liste og skriver ut innholdet.
""" Simple module demonstrating lists and loops """ S=['ole','adam','marit','silvio','petronella'] # dump it print S # simplest for name in S: print name # for loop for ix in range(0,len(S)): print S[ix] #while loop ix=0 while ix < len(S): print S[ix] ix+=1
Lister og sortering.
""" Simple module demonstrating lists and sorting """ S=['ole','adam','marit','silvio','petronella'] for name in S: print name print '------ reversed -------' S.reverse() for name in S: print name print '--- sorted -----' S.sort() for name in S: print name print '---- sorted and then reversed ---' S.reverse() for name in S: print name
Lister av lister, og sortering.
""" Simple module demonstrating lists and sorting name and year of birth """ import datetime S=[['ole',1998],['adam',2002],['marit',1973],['silvio',2002],['petronella',1956]] # dump it for person in S: print person # sort sets as they are S.sort() for person in S: print person # sort on age def compareYearOfBirth(a,b): return a[1] - b[1] S.sort(compareYearOfBirth) y=datetime.datetime.today().year for person in S: print person[0]+' is '+str(y-person[1])+' years old'
Dictionary
""" Working with dicuionaries """ import datetime D={} D['ole']=['mysen',1998] D['jens']=['halden',2005] D['peder']=['moss',2001] # dump it print D # loop it keylist=D.keys() for k in keylist: print k+' is from '+D[k][0]+' and is born in '+str(D[k][1]) # iterate for k, v in D.iteritems(): print k+' is from '+v[0]+' and is born in '+str(v[1]) # sort on name keylist=D.keys() keylist.sort() for k in keylist: print k+' is from '+D[k][0]+' and is born in '+str(D[k][1]) # sort on age items=D.items() y=datetime.datetime.today().year def compareYearOfBirth(p1,p2): return p2[1][1]-p1[1][1] items.sort(compareYearOfBirth) for item in items: print item[0]+' is '+str(y-D[item[0]][1])+' years old, from '+D[item[0]][0]