Python Mer om datatyper Heltal - 3 Flyttal - 2,456 Listor - [1,2,3,4] Strängar - spam! Datatyper Dictionaries - {1: camelot,2: shrubbery } Tupler - (1,2,3,) 1
Lite om strängar Strängar innehåller specialtecken Dessa vill man ofta ignorera Nyrad, tab Lite om strängar >>> a = """a... b... c""" >>> a 'a\nb\nc' >>> print a a b c >>> len(a) 5 Dessa räknas som blanktecken, "whitespace". Kan ställa till problem när man t.ex. vill räkna ordlängd el.dyl. 2
Lite om strängar >>> b = " lancelot " >>> b ' lancelot ' >>> newb = b.strip() >>> newb 'lancelot' strip() tar bort whitespaces i början och slutet av strängar alltså även \n och \t (och \r) Tupler Tupler är ungefär som listor, men immutable Detta ger en viss integritet Kan användas på ställen där listor inte kan användas Stödjer index, slice, konkatenering, for-inloopar... Har i princip inga metoder 3
Tupler en tom tupel: () treobjektstupel: (5,2,'hello') nästlad tupel: (2,5,('hello','polly'),8) tupel med 1 objekt: (1,) jämförelse: >>> 1==(1) True >>> 1==(1,) False Tupler >>> tup = (1,2,3,4) >>> tup[0] 1 >>> tup[1:-1] (2, 3) >>> 2 in tup True >>> 8 in tup False >>> for i in tup: print i*i 1 4 9 16 4
Tupler >>> tup+('hej') Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> tup+('hej') TypeError: can only concatenate tuple (not "str") to tuple >>> tup+('hej',) (1, 2, 3, 4, 'hej') >>> tup+tuple("hej") (1, 2, 3, 4, 'h', 'e', 'j') Tupler >>> tup[0] = 4 Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> tup[0] = 4 TypeError: 'tuple' object does not support item assignment 5
Tupler def separatecharacters(astring): vows=0 cons=0 vowels="aoueiy" for char in astring: if char in vowels: vows = vows + 1 else: cons = cons + 1 return (vows, cons) print separatecharacters("an african or a european swallow") Tupler är immutable >>> tup = (8,5,4,9,1) >>> temp = list(tup) >>> temp.sort() >>> tup=tuple(temp) >>> tup (1, 4, 5, 8, 9) 6
Extra info: nästlade index >>> L = [1,2,[1,2,3],4] >>> L[1] 2 >>> L[2] [1, 2, 3] >>> L[2][0] 1 >>> L[2][0]="SPAM!" >>> L [1, 2, ['SPAM!', 2, 3], 4] Extra info: nästlade index >>> s="red. no! blue!" >>> s[0] 'r' >>> s[0][0] 'r' >>> s[0][0][0] 'r' 7
Tupler Element i tupler är inte nödvändigtvis immutable: >>> tup = (1,2,[1,2,3],3) >>> tup[2] [1, 2, 3] >>> tup[2][1] = "SPAM!" >>> tup (1, 2, [1, 'SPAM!', 3], 3) Dictionaries Nyckel-värde-par Inte sekventiella, stödjer alltså inte index & slice Mutable 8
Dictionaries En variabel med dictionary: variable = {key:value, key:value...} Key måste vara immutable; tuple, sträng, tal Varje nyckel är unik Value kan vara vad som helst Value behöver inte vara unik Dictionaries Exempel på metoder (finns många): get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. has_key(...) D.has_key(k) -> True if D has a key k, else False items(...) D.items() -> list of D's (key, value) pairs, as 2- tuples keys(...) D.keys() -> list of D's keys pop(...) D.pop(k[,d]) -> v, remove specified key and return the corresponding value If key is not found, d is returned if given, otherwise KeyError is raised popitem(...) D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty values(...) D.values() -> list of D's values 9
Exempel: en ordbok Dictionaries >>> swenglish = {"buskage":"shrubbery", "sill":"herring", "svala":"swallow"} >>> swenglish["sill"] 'herring' Inte index, utan nyckel Litet exempel: Dictionaries >>> spamdict = {} >>> spamdict[2] = 'eggs' >>> spamdict[5] = 'tomato' >>> spamdict[1] = 'spam' >>> spamdict {1: 'spam', 2: 'eggs', 5: 'tomato'} >>> spamdict[5] = 'spam' >>> spamdict {1: 'spam', 2: 'eggs', 5: 'spam'} 10
Dictionaries >>> spamdict = {1:"spam",5:"tomato",2:"eggs",3:"spam"} >>> spamdict {1: 'spam', 2: 'eggs', 3: 'spam', 5: 'tomato'} >>> spamdict[2] 'eggs' >>> spamdict[2][0] 'e' >>> spamdict.keys() [1, 2, 3, 5] >>> 5 in spamdict True >>> spamdict.has_key(8) False Dictionaries >>> spamdict.values() ['spam', 'eggs', 'spam', 'tomato'] >>> spamdict[2] = "sausage" >>> spamdict {1: 'spam', 2: 'sausage', 3: 'spam', 5: 'tomato'} >>> spamdict[8] = 'viking' >>> spamdict {1: 'spam', 2: 'sausage', 3: 'spam', 8: 'viking, 5: 'tomato'} >>> spamdict = {1:"spam",5:"tomato",2:"eggs",3:"spam", 1:"eggs"} >>> spamdict {1: 'eggs', 2: 'eggs', 3: 'spam', 5: 'tomato'} 11
Dictionaries spamdict = {1:"spam",5:"tomato",8:"eggs",3:"spam"} for key in spamdict.keys(): print "Key:",key,"Value:",spamDict[key] Key: 8 Value: spam Key: 2 Value: eggs Key: 3 Value: spam Key: 5 Value: tomato Dictionaries Man kan inte sortera en dictionary Man vill ofta presentera innehållet på ett sorterat sätt En lösning: Skapa en lista av nycklarna, sortera den, presentera detta 12
Dictionaries spamdict = {1:"spam",5:"tomato",8:"eggs",3:"spam"} keylist = spamdict.keys() keylist.sort() for key in keylist: print "Key: ", key, "Value: ", spamdict[key] Ett vanligt problem >>> spamdict = {1: 'viking', 2: 'eggs', 3: 'spam', 5: 'tomato'} >>> spamdict[2] 'eggs' >>> spamdict[9] Traceback (most recent call last): File "<pyshell#94>", line 1, in <module> spamdict[9] KeyError: 9 13
Ett vanligt problem Man kan tänka sig en dictionary när man ska hålla räkningen på något, som en tabell Sedan tänker man sig en funktion som sköter uppdateringen av dictionaryn Man vill undvika KeyError Kod resultdict = {} def incdict(key): if incdict.has_key(key): resultdict[key] = resultdict[key] + 1 else: resultdict[key] = 1 14
En vanlig lösning get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. alltså: resultdict = {} def incdict(key): resultdict[key] = resultdict.get(key, 0) + 1 15