Topic 03 Data Types
Topic 03 Data Types
x+y Addition
x–y Subtraction
x*y Multiplication
x/y Division
For example:
Expression in Math:
π π
ax2 + bx + c, 3sin + (5cos − 2)2
4 6
Expression in Python: ?
∘ Code Examples
Basic Calculation
Using Variables
In [3]: a = 20
b = 0O24
c = 0x14
d = 0b10100
e = 20.0
a, b, c, d, e
In [4]: a = 123
b = bin(a)
o = oct(a)
h = hex(a)
a, b, o, h
Out[5]: 123
In [9]: a = 20
b = 20
c= 20
x = 1
a*x**2 + b*x + c
Out[9]: 60
In [10]: dir()
Out[10]: ['In',
'Out',
'_',
'_1',
'_2',
'_3',
'_4',
'_5',
'_6',
'_7',
'_8',
'_9',
'__',
'___',
'__builtin__',
'__builtins__',
'__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'__vsc_ipynb_file__',
'_dh',
'_i',
'_i1',
'_i10',
'_i2',
'_i3',
'_i4',
'_i5',
'_i6',
'_i7',
'_i8',
'_i9',
'_ih',
'_ii',
'_iii',
'_oh',
'a',
'b',
'c',
'd',
'e',
'exit',
'get_ipython',
'h',
'o',
'o1',
'open',
'quit',
'x']
Out[11]: 8.550812267870867
Out[12]: Decimal('2.22')
Out[13]: 2.2200000000000006
Out[14]: True
Out[16]: -2.281718171540956
In [ ]:
Out[17]: Decimal('3.3')
Out[18]: 4.83723613240981
Out[20]: 11481306952742545242328332011776819840223177020886952004776427368257662613923703138566594863165062699184459646389874627734471189608630553314259313561666531853912998914531228000
06887791482400448714289269900634862447816154636463883639473170260404663539709049965581623988089446296056233116495361642219703326813441689089844585056023794848079140589009347765
00429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786
419432054508915275783882625175435528800822842770817965453762184851149029376
Out[21]: 2.2250738585072014e-308
Bool Type
Expression in Logics:
¬(a ∧ b), ¬a ∧ b ∨ (c ∨ d)
Expression in Python:
∘ Code Examples
Relational Expressions
In [22]: x = 3
y = 6
z = 8
x < y < z, x == y, x == 3, y != x, y >= x, x < y > z, 1.1 + 2.2 == 3.3, 1 + 2 == 3
Logical Expressions
In [23]: x = True
y = False
x and y, x or y, not x, 3 < 5 and 5 >= 8, x == 1, y == 0
In [24]: x = 100
y = 100
id(x), id(y), x is y
In [25]: s0 = u'\u20AC'
print(s0)
\a Bell
\b Backspace
\n Newline (linefeed)
\r Carriage return
\t Horizontal tab
∘ Code Example
Define a string variable in different ways
ten years"""
s4 = "The list company's age is: \nten years"
s5 = "The list company's age is:" + "\n" + "ten years"
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
ten years
The list company's age is:
ten years
The list company's age is:
ten years
Print Objects
Format Strings
https://realpython.com/python-string-formatting/
In [ ]:
In [ ]: sr = r'C:\new\text.dat'
s = 'C:\new\text.dat'
print(sr, len(sr))
print(s, len(s))
C:\new\text.dat 15
C:
ew ext.dat 13
In [ ]: dir(str)
Out[ ]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
In [ ]: '周⽴刚'.encode().decode()
Out[ ]: '周⽴刚'
0x6fb3 0x95e8
澳⻔
澳
In [ ]: codes = '€'.encode()
print(codes)
sam = codes.decode()
print(sam)
b'\xe2\x82\xac'
€
In [ ]: code = b'\xE2\x82\xAC'
print(code.decode())
Out[ ]: True
In [ ]: print('\u20AC'), print(b'\xE2\x82\xAC'.decode())
€
€
Out[ ]: (None, None)
∘ Basic Operations
In [ ]: s0 = 'hello,' ' world!'
s1 = 'hello,' + ' world!' # Concatenation: a new string
s2 = 'ab'*30 # Repetition: like '-'+'-'+...
print(s0)
print(s1)
print(s2)
hello, world!
hello, world!
abababababababababababababababababababababababababababababab
In [ ]: s = 'HELLO, WORLD!'
len(s)
Out[ ]: 13
In [ ]: s[-6:]
Out[ ]: 'WORLD!'
In [ ]: s[0:5:2]
Out[ ]: 'HLO'
In [ ]: s = "HELLO, WORLD!"
print(s)
print(s[:])
print(s[::-1])
print(s[0] + "\t" + s[5] + "\t" + s[-1]) # indexing
print(s[0:5] + ' ' + s[0:-1:2] + ' ' + s[:-2])
# --------------Slice object----------------------------
so = slice(None, None, 2) #slice(start, end, step)
print(s[so]+'\n'+s[::2])
HELLO, WORLD!
HELLO, WORLD!
!DLROW ,OLLEH
H , !
HELLO HLO OL HELLO, WORL
HLO OL!
HLO OL!
∘ String converstion
In [ ]: '1' + 1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-cc892b1f57d5> in <module>
----> 1 '1' + 1
In [ ]: type('1'), type(1)
In [ ]: # float('1.1') + 1
str(1)
len(str(2**200))
Out[ ]: 61
In [ ]: float('1.1') + 2.2
Out[ ]: 3.3000000000000003
In [ ]: str(2)
Out[ ]: '2'
In [ ]: int('1') + 1
Out[ ]: 2
In [ ]:
∘ Changing Strings
In [ ]: s = "Macau is beautiful!, Macau is a small city!"
s
In [ ]: s.replace('Macau', 'Zhuhai', 1)
In [ ]: help(s.replace)
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
In [ ]: dir(s)
Out[ ]: 78
In [ ]: s = 'Macau is beautiful!'
s = s.replace("Macau", "Zhuhai")
s
▹ String Methods
Attribute fetches (对象属性访问)
An expression of the form object.attribute means “fetch the value of attribute in object.”
Methods (调⽤对象⽅法)
Putting above two together allows us to call a method of an object. The method call expression: object.method(arguments)
--- Align --- S.ljust(width [, fill]) S.center(width [, fill]) S.rjust(width [, fill]) S.zfill(width) --- Type --- S.isalnum() S.isalpha() S.isdecimal() S.isdigit() S.isidentifier() S.islower() S.isnumeric() S.isprintable() S.isspace() S.istitle() S.isupper() -- Changing -- S.capitalize() S.casefold()
S.title() S.upper() S.lower() S.swapcase() S.translate(map) S.maketrans(x[, y[, z]])S.lstrip([chars]) S.strip([chars]) S.rstrip([chars]) S.join(iterable) S.split([sep [,maxsplit]]) S.splitlines([keepends]) S.rsplit([sep[, maxsplit]]) S.rpartition(sep) --- Index, Find, Replace --- S.count(sub [,
start [, end]]) S.encode([encoding [,errors]]) S.partition(sep) S.endswith(suffix [, start [, end]]) S.replace(old, new [, count]) S.expandtabs([tabsize]) S.rfind(sub [,start [,end]]) S.find(sub [, start [, end]]) S.rindex(sub [, start [, end]]) S.format(fmtstr, *args, **kwargs) S.startswith(prefix
[, start [, end]]) S.index(sub [, start [, end]])
In [ ]: s = 'Macao'
s.center(30, '\u62ac')
Out[ ]: '抬抬抬抬抬抬抬抬抬抬抬抬Macao抬抬抬抬抬抬抬抬抬抬抬抬抬'
⎡ 11 ⎤
x x12 ⋯ x 1n
⎢
⎢ ⋮ ⋮ ⋮ ⋮ ⎥⎥
⎣x xn2 ⋯ xmn ⎦
m1
Tensor(张量)3D:
Expression in Python:
Scalar ⇒ Simple Data Type: int, float, bool, string, ...
Vector, Matrix, Tensor 3D/ND ⇒ Complex Data Type (Data collection/container):
List
Dictionary
Tuple
Set, ...
String can be taken as a collection of characters.
Data collection is a container of different types of data.
List
Lists are Python's most flexible ordered collection object type.
Characteristics of List
Ordered collections of arbitrary objects
Accessed by offset/position
Variable-length, heterogeneous, and arbitrarily nestable
Mutable
Arrays of object references
List vs String
String ⟶ 字符串 List ⟶ 数据串
In [ ]: s = 'hello!'
ls = ['h', 'e', 'l', 'l', 'o', '!']
s2 = ''.join(ls)
print(s, s2)
ls2 = list(s)
print(ls, ls2)
hello! hello!
['h', 'e', 'l', 'l', 'o', '!'] ['h', 'e', 'l', 'l', 'o', '!']
In [ ]: # s[0] = 'I'
print(s[0])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-d6f3b193531a> in <module>
----> 1 s[0] = 'H'
In [15]: help(s.replace)
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
List's Literals & Operations
Operations Interpretation -------------------------------------------------------------------- L = [] An empty list L = [123, 'abc', 1.23, {}] Four items: indexes 0..3 L = ['Bob', 40.0, ['dev', 'mgr']] Nested sublists L = list('spam') List of an iterable’s items L = list(range(-4, 4)) List of successive
integers -------------------------------------------------------------------- L[i] Index L[i][j] Index of index L[i:j] Slice len(L) Length -------------------------------------------------------------------- L1 + L2 Concatenate, repeat L * 3 -------------------------------------------------------------------- 3 in L
Membership -------------------------------------------------------------------- L.append(4) Methods: growing L.extend([5,6,7]) L.insert(i, X) --------------------------------------------------------------------- L.index(X) Methods: searching L.count(X) ---------------------------------------------------------
------------ L.sort() Methods: sorting, reversing, L.reverse() L.copy() Copying (3.3+) L.clear() Clearing (3.3+) --------------------------------------------------------------------- L.pop(i) Methods, statements: shrinking L.remove(X) del L[i] del L[i:j] L[i:j] = [] ---------------------------------------
------------------------------- L[i] = 3 Index assignment, slice assignment L[i:j] = [4,5,6] ---------------------------------------------------------------------- L = [x**2 for x in range(5)] List comprehensions and maps list(map(ord, 'spam')) --------------------------------------------------------------------
---
Introduction to List's Function
Lists in Action
In [3]: L0 = [1, 2, 3]
L1 = [4, 5, 6]
L2 = ['a', 1.25, L0]
# L0 + L1
L0 * 2
# L2,
# 3 in L0
# L0 + list('abc')
Out[3]: [1, 2, 3, 1, 2, 3]
In [4]: L2
In [2]: L2 = list(range(1,41))
print(L2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
In [12]: L2 = list(range(1,41))
del L2[:5]
print(L2)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
In [11]: print(L2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
In [9]: L0 = [1, 2, 3]
L0.append('abc')
L0
Out[26]: 3
Out[27]: [0.9876131375307133,
0.32637775354448384,
0.5452252886358093,
0.4404228570992531,
0.35873274133019406,
0.969737764650136,
0.18496098267691785,
0.16126736749201231,
0.2621545282338793,
0.8899567581363814]
In [19]: rets.sort()
rets.reverse()
rets
Out[19]: [0.9859582280497966,
0.9243012766252489,
0.8797263356487407,
0.752239932110347,
0.7003314363317287,
0.6499712105638575,
0.49908293235185375,
0.47642222220159036,
0.4762869565224409,
0.3776038279454894]
In [21]: help(rets.sort)
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.
In [19]: # rets.sort(reverse=True)
rets
Out[19]: [0.9560069499728105,
0.9098878155961849,
0.7713933468131645,
0.6857339544590342,
0.6333260084398755,
0.5349982465408022,
0.49270975501254,
0.42325726732029456,
0.18090519650835946,
0.08122229081948418]
In [34]: L0 = 32
L1 = L0
L0 = 54
id(L0), id(L1)
In [37]: L0 = 'hello'
L1 = L0
L0 = 'world'
L1
Out[37]: 'hello'
In [14]: L1
In [22]: a = [1, 8, 2, 5, 7]
a.sort(reverse=True)
a
# a
# a.reverse()
# a
Out[22]: [8, 7, 5, 2, 1]
In [34]: L0.pop(2)
L0
Dictionaries
Dictionaries are unordered collections whose items are stored and fetched by key , instead of by positional offset in list.
Characteristics of Dictionary
Accessed by key, not offset position
Unordered collections of arbitrary objects
Variable-length, heterogeneous, and arbitrarily nestable
Mutable
Tables of object references (hash tables)
Dictionaries in Action
In [1]: D = {'spam': 2, 'ham': 1, 'eggs': 3}
D2 ={'ham':4, 'toast':6}
In [5]: 'ham' in D
Out[5]: True
In [41]: D['fish'] = 5
D
In [42]: D.update(D2)
D
In [43]: v = D.pop('toast')
D
# v
Usage Notes
Tuples
Tuples work exactly like lists, except that tuples can't be changed in place, i.e. immutable.
Characteristics of Tuples
Ordered collections of arbitrary objects
Accessed by offset
Immutable
Fixed-length, heterogeneous, and arbitrarily nestable
Arrays of object references
In [28]: dir(())
Out[28]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'count',
'index']
Tuples in Action
In [29]: t0 = (30)
t1 = (30,)
type(t0), type(t1)
# t0, t1 # t0 is an integer, t1 is a tuple, !!the output of this line is a nested tuple
In [46]: T = (1, 3, 2, 4, 2, 5, 2)
T.index(2), T.index(2,3), T.count(2), T.index(2, T.count(2))
Out[46]: (2, 4, 3, 4)
In [30]: help(().index)
In [49]: T = list(T)
T[1] = 8
T = tuple(T)
T
Out[49]: (1, 8, 2, 4, 2, 5, 2)
The immutability of tuples provides some integrity—you can be sure a tuple won’t be changed through another reference elsewhere in a program, but there’s no such guarantee for lists. Tuples and other
immutables, therefore, serve a similar role to “constant” declarations in other languages.
Set
An unordered collection of unique and immutable objects that supports operations corresponding to mathematical set theory.
Characteristics of Set
Items are stored only once in a set, i.e. no duplication
Items can not be revised directly
Set can be revised by internal methods
In [19]: so = {1, 3, 5, 7}
se = {2, 4, 6, 8}
s = set(range(5))
print(f's={s}')
soe = so | se # OR
s0 = s & so # AND
s1 = s - so # Difference
s2 = s ^ so # XOR
so > se, so < se
print(soe)
print(s0)
print(s1)
# dir(so)
# help(s0.difference_update)
# so.difference_update(s)
help(so.add)
s={0, 1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 3}
{0, 2, 4}
Help on built-in function add:
In [56]: s = {1, 4, 7}
s.add('abc')
s