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 yearOfBirthKey(a): return a[1] S.sort(key=yearOfBirthKey) y=datetime.datetime.today().year for person in S: print (person[0]+' is '+str(y-person[1])+' years old')
Dictionary
""" Working with dictionaries """ import datetime D={} D['alex']=['mysen',1998] D['jens']=['halden',2005] D['peder']=['moss',2001] print('------------- dump ------------') print(D) print('------------- loop ------------') keylist=D.keys() for k in keylist: print (k,' is from ',D[k][0], ' and is born in ',str(D[k][1])) print('------------- sort on name ------------') keylist=sorted(D) for k in keylist: print (k,' is from ',D[k][0], ' and is born in ',str(D[k][1])) print('------------- sort decending on age ------------') y=datetime.datetime.today().year def yearOfBirthKey(a): return a[1][1] items=D.items() mitems=sorted(items,key=yearOfBirthKey) for item in mitems: print (item[0],' is ',str(y-D[item[0]][1]), ' years old, from ',D[item[0]][0]) print('------------- sort ascending on age ------------') y=datetime.datetime.today().year def yearOfBirthKey1(a): return -a[1][1] items=D.items() mitems=sorted(items,key=yearOfBirthKey1) for item in mitems: print (item[0],' is ',str(y-D[item[0]][1]), ' years old, from ',D[item[0]][0])
Tuple
Tuples er i korthet lister som ikke kan endres.
# tuples t=("ole","jens","per") print(t) def collectThem(t1,t2): return t1+t2 all=collectThem(("a","b"),("c","d")) print (all)