Download Python Data Types

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming with Python
Lecture 1: Elements of Python
IPEC Winter School 2015
B-IT
Dr. Tiansi Dong & Dr. Joachim Köhler
Python Types
●
Numbers
●
Strings
'spam', “hello world”, b'a\x01c'
●
Lists
[1,[2,3],[3,'three']]
●
Dictionaries {'name': 'Bush','firstname':'Geoge W.'}
●
Tuples
(1, 'X')
●
Files
mfile = open('script0.py', 'r')
●
Sets
x = set('abc'), x={'a', 'b', 'c'}
●
Other core types
●
Program unit types Functions, modules, classes
●
Implementation-related types Compiled code,stack traceback
1234,3.1324, 1+8j, 1e3
Booleans, types, None
Python Types: Strings 1
●
Python strings are read-only sequences of chars.
>>>S = 'hello world!'
>>>S[:-1]
>>>len(S)
'hello world'
12
>>>S[-1:2]
>>>S[11]
''
'!'
>>>S.find('h')
>>>S[-1]
0
'!'
>>>S.replace('o', 'OO')
>>>S[1:111]
hellOO wOOrld!
'ello world!'
Python Types: Strings 1
●
Python strings are read-only sequences of chars.
>>>S
>>>S = 'H' + S[1:]
hello world!
'Hello world!'
>>>S[0]='H'
>>>dir(S)
Traceback (most recent
call last):
File "<pyshell#6>",
line 1, in <module>
S[0]='H'
TypeError: 'str' object
does not support item
assignment
Python Types: Strings 3
>>>S.split('o')
['Hell', 'w', 'rld!']
>>>S.upper()
HELLO WORLD!
>>>'hello %s %s' % ('world', '!')
hello world !
>>>'hello {0}{1}'.format('world','!')
hello world!
Python Types: Strings 2
●
String structure in Python
0
1
h
[:
2
e
3
l
4
l
o
w o
r
l
-2
-1
d
! \n
:]
Python Types: Strings 3
>>>help(S.replace)
help on built-in function replace:
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of
substring old replaced by new. If the optional
argument count is given, only the first count
occurrences are replaced.
Python Types: Strings 5
●
String format
%[(name)][flags][width][.precision]typecode
+|%
-
s|d|f|...
5
d
>>>'%-5d'%12
'12
'
>>>'%5d'%12
'
12'
>>>reply = “Hello %(name)s! Your bonus is %(bonus)s”
>>>value = {'name':'Bob', 'bonus':1000}
>>>replay % value
'Hello Bob! Your bonus is 1000'
Python Types: Strings 6
●
String formatting method call
>>>template = '{0}, {1}, {2}'
>>>template.format('hello','world','!')
'hello, world, !'
>>>template = 'hello {name}, your bonus is {bonus}'
>>>template.format(name='Bob', bonus=1000)
'hello Bob, your bonus is 1000'
>>>import sys
>>>'My {1[pc]} runs {0.platform}'.format(sys, {'pc':'MAC'})
'My MAC runs darwin'
Python Types: Strings 7
●
String formatting method call
>>>'My {config[pc]} runs {sys.platform}'.format(sys=sys,
config={'pc':'MAC'})
'My MAC runs darwin'
>>>'Hello {0:<8}, your bonus is {1:-=10}'.format('Bob',
1000)
'Hello Bob
, your bonus is ------1000'
>>> 'Hello {0:^8}, your bonus is {1:-^10}'.format('Bob',
1000)
'Hello
Bob
, your bonus is ---1000---'
>>> 'Hello {0:>8}, your bonus is {1:->10}'.format('Bob',
1000)
'Hello
Bob, your bonus is ------1000'
Python Types: List 1
List is an important data structure in AI. It is readable, writable, and can
be nested with any object
●
List is recursively defined
>>> Lst = []
>>> Lst = [1,2,3,'a','b','c']
>>> Lst[:-1]
[1,2,3,'a','b']
>>> Lst + ['hello']
>>> Lst.append('world')
>>>Lst
[1,2,3,'a','b','c','world']
Python Types: List 2
>>>Lst.reverse()
['world', 'c', 'b', 'a', 3, 1]
>>>Lst.sort()
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
Lst.sort()
TypeError: unorderable types: str() < int()
>>>L = ['c','b','a']
>>> L.sort()
>>> L
['a', 'b', 'c']
Python Types: List 3
●
Nested list representing Matrixes or multidimensional arrays
>>>M = [[1,2,3],[4,5,6],[7,8,9]]
>>>M[1]
[4,5,6]
>>>M[1][2]
6
●
List Comprehension is an easy way to construct new lists
Syntax: '[ f(x) for x in <list>]'
>>>[c*2 for c in 'hello']
['hh', 'ee', 'll', 'll', 'oo']
>>>[row[1] for row in M]
[2,5,8]
Python Types: Tuple 1
●
Tuples are read-only lists
>>>Tpl = (1,2,3,4)
>>>len(Tpl)
4
>>>Tpl[0]
1
>>>Tpl.index(4)
3
>>>Tpl0 = (1,2,3, [11,22])
>>>Tpl0[3][1]
22
Python Types: Tuple 2
●
Tuples are read-only lists
>>>Tpl0.append(4)
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
Tpl0.append(4)
AttributeError: 'tuple' object has no attribute
'append'
Python Types: Set 1
●
●
●
A mathematical set is an unordered collection with unique elements
A Python set is an unordered collection with unique and hashable
elements, to simulate mathematical set operations
What does hash mean in computer science?
–
A mapping from something into numbers
Python Types: Set 2
●
Why Python sets only allow hashable elements?
–
Set operations are expensive
–
In Python, sets are mapped (hashed) to sets of numbers, so that
operations on sets are achieved much faster.
–
The pre-condition is that original sets are read-only.
Python Types: Set 3
●
Set operations in Python 2.6
>>>S0 = set('abc')
>>>S0
{'a', 'c', 'b'}
>>>S1 = set('abxyz')
>>>S1
{'a', 'b', 'y', 'x', 'z'}
>>>'a' in S0
True
>>>S0 – S1
{'c'}
Python Types: Set 4
●
Set operations in Python 2.6
>>>S2 = set('abcd')
>>>S0 < S2
True
>>>S0.intersection(S1)
{'a', 'b'}
>>>S0.union(S1)
{'a', 'c', 'b', 'y', 'x',
'z'}
>>> S0.remove('a')
Python Types: Set 5
●
Set operations in Python 2.6
>>> S0
{'c', 'b'}
>>> S0.remove('x')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
S0.remove('x')
KeyError: 'x'
Python Types: Set 6
●
Set operations in Python 3.0
>>>{1,2,3} & {1,2}
{1,2}
>>>{1,2,3} | {3,4}
{1,2,3,4}
>>>{1} – {1}
set()
●
Set comprehension
>>>{x **2 for x in [1,2,3]}
{1,9,4}
>>>{x **2 for x in {1,2,3}}
{1,9,4}
Python Types: Dictionaries 1
●
The Python Dictionary can be understood as an extension of the Python
set, such that each set element is mapped into an object
>>>Dic1 = {'name':'Bob', 'job':'no', 'age':10}
>>>Dic2 = {'name':{'first':'Marie','last':'Curie'},
'affiliation':'Sorbonne'}
>>>Dic1['name']
'Bob'
>>> list(Dic1.keys())
['age', 'job', 'name']
>>> Ks = list(Dic1.keys())
Python Types: Dictionaries 2
>>> for key in Ks:
print(key, '=>', Dic1[key])
age => 10
job => no
name => Bob
Python Types: Dictionaries 3
>>>Dic1.['address']
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
Dic1['address']
KeyError: 'address'
>>>Dic1.get['address', 0]
0
>>>Dic1['address'] if 'address' in D else 0
0
>>>dir(Dic1)
Python Types: Numbers 1
●
Try first:
>>> 123+222
345
>>> 2 ** 3
#2 to the power 3
8
>>> len(str(2 ** 5)) #how many digits
2
>>>import math
>>>math.pi
3.141592653589793
Python Types: Numbers 2
●
Try first:
>>>import random
>>>random.random()
0.9311179915010321
>>>dir(random)
Python Types: Numbers 3
●
●
Why do we introduce Python numeric types now, after we introduced strings,
lists, tuples, sets, dictionaries?
Python numeric Types
–
Integers
–
Floating-point numbers 1.0, 3.1415, 1.414, 4.0e+12
–
Complex numbers
–
Fixed-precision decimal numbers
–
Rational fraction numbers
–
Sets
–
{} is not the empty set
1,2,3
3+4j, 3.1+4.2j
decimal.Decimal('0.1')
fractions.Fraction(1,3)
{1,2,3}, {'a', 'b', 3}
Python Types: Numbers 4
●
Python numeric Types
–
Booleans
–
A variety of numeric built-ins and modules,
True, False
True + 1, False -1
●
Pow, abs, round, int, hex, bin, ...
●
math, NumPy, SciPy, random, ...
Python Types: Numbers 5
●
Python expressions
–
X if Y else Z
–
X or Y
–
X and Y
–
not X
–
X in Y, X not in Y
–
X is Y, X is not Y
–
X < Y, X <= Y, X == Y, X > Y, X >= Y, X != Y
–
X | Y, X ^ Y, X & Y
–
X << Y, X >> Y
–
X + Y, X – Y, X * Y, X % Y, X / Y, X // Y
–
int(3.1415), int('123'), float(3), str(1234)
Python Types: Numbers 6
●
Numeric accuracy
>>>0.1+0.1+0.1-0.3
5.551115123125783e-17
>>>from fractions import Fraction
>>>Fraction(1,10)+Fraction(1,10)+Fraction(1,10)Fraction(3,10)
Fraction(0,1)
>>>(3.1415).as_integer_ratio()
(7074029114692207, 2251799813685248)
>>>from fractions import Fraction
>>> Fraction.from_float(1.75)
Fraction(7, 4)
Python Types: Numbers 7
●
Numeric accuracy
>>> Fraction.from_float(5.4)
Fraction(3039929748475085, 562949953421312)
>>> Fraction.from_float(5.4).limit_denominator(10)
Fraction(27, 5)
>>> 5.4 + Fraction(7.4)
12.8
Python Types: Files 1
●
Files are a core type of Python, is created using the built-in open
function:
>>>mfile = open('first_file.txt', 'w')
●
●
●
●
The second parameter of is the processing mode, whose values can be
'r', 'w', 'a'(open and append text to the end of the file), 'b'(binary), 't'(text),
'+'(read and write), 'U'(universal newline mode )
The default mode is 'rt' (open for text reading).
For binary random access, the mode 'w+b' opens and truncates the file
to 0 bytes. 'r+b' opens the file without truncation.
Basic file operations
>>>mfile.write('hello\n')
6
>>>txt = mfile.read()
Python Types: Files 2
>>>str = mfile.read() #read whole file into a string
>>>str = mfile.read(N) #read maximum N chars
>>>str = mfile.readline() #read next line
>>>lst = mfile.readlines() #read whole file into a
#list of line strings
>>>mfile.writelines(aList) #write all line strings in
#a list into the file
>>>mfile.flush()
#flush output buffer
>>>mfile.close()
>>>open('file0.txt', encoding='latin-1') #python 3.0
Python Types: Files 3
●
Python's standard library pickle is an tool that allows as to store
almost any Python object into files directly.
>>>Dic = {'a': 123, 'b'=3.1415}>
>>>dFile=open('Dic.pk', 'wb')
>>>import pickle
>>>pickle.dump(Dic,dFile)
>>>dFile.close()
>>>dic_file=open('Dic.pk', 'rb')
>>>mDic=pickle.load(dic_file)
>>>mDic
{'a': 123, 'b'=3.1415}
>>>dic_file.close()
Python Dynamic Typing 1
●
No declaration statements in Python
>>>a = 3
>>>a = 'hello world!'
a
3
3
a
●
hello world!
Garbage-collection is performed automatically
Python Dynamic Typing 2
●
Shared references in Python
>>>a = 3
>>>b = a
a
3
b
●
●
Variables are pointers to values; assignment variable a to variable b
adds a new pointer b to the value pointed by a.
Assignment introduces references, not copy
Python Dynamic Typing 3
●
Object copy in Python
●
== vs. is
>>>L1 = [2,3,4]
>>> L1 == L3
>>>L3 = L1
True
>>>L2 = L1[:]
>>> L1 is L2
>>>L1[0]= 234
False
>>>L1
>>> L1 is L4
[234,3,4]
False
>>>L2
●
>>> L1 == L3
[2,3,4]
True
>>>import copy
>>> L1 is L3
>>>L4 = copy.copy(L1)
True
Python Dynamic Typing 4
●
Small integers and strings are
cached and reused
>>>X = 12
>>>Y = 12
>>>X is Y
True
●
To get the object's reference
number
>>>import sys
>>>sys.getrefcount(L3)
3
>>>sys.getrefcount(1)
927
Related documents