You are on page 1of 14

TA1103_1104

Written and Edited by Dio H.


#@@ Codes didn't appear in class of in PPT.

0. Warm up
In [1]: #Q1
x=3
y=2
#We want to get -> (3,2)

#----------------------------------------------------#
print(f'({x},{y})')
print('(%d,%d)'%(x,y))
print('({0},{1})'.format(x,y))
print('({first},{second})'.format(first=x,second=y))

(3,2)

(3,2)

(3,2)

(3,2)

In [9]: #Q2
#reverse list
data=[1,2,3,4,5,6,7,8,9,10]

#(1) We want to get -> [10,9,8,7,6,5,4,3,2,1]
#(2) We want to get -> [10,8,6,4,2]
#(3) We want to get -> [9,7,5,3,1]

#--------------------------------------------#

#Ans
# [1,2,3,4,5,6,7,8,9,10]
#Index 0 1 2 3 4 5 6 7 8 9
print(data[::-1])
print(data[9::-1])
print(data[-1::-1])
print('-----------------------------')
print(data[::-2])
print(data[9::-2])
print(data[-1::-2])
print('-----------------------------')
print(data[8::-2])
print(data[-2::-2])

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

-----------------------------

[10, 8, 6, 4, 2]

[10, 8, 6, 4, 2]

[10, 8, 6, 4, 2]

-----------------------------

[9, 7, 5, 3, 1]

[9, 7, 5, 3, 1]

1.Tuples (a,b,c ...)


Faster than List.
Protect contents.
Can't change value (immutable -> can't use appended, deleted, and editable).
in order

1.1 Tuple vs List


In [10]: #list
mylist=[] #list() is ok too.
print(mylist)
print(type(mylist))
print(dir(list)) #Check 最後幾個

print("----------------------------------------------------------------------------------------------------------
# tuples
mytup=()
print(mytup)
print(type(mytup))
print(dir(mytup))

[]

<class 'list'>

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format


__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__i
nit_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__red
uce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub
classhook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sor
t']

----------------------------------------------------------------------------------------------------------------
----------------------------------

()

<class 'tuple'>

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',


'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__i
ter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr_
_', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

1.2 Create Tuple


In [11]: print("-------1-------")
t1=() # empty
print(t1)
print(type(t1))

print("-------2-------")
t2=(1,) # For only one value in a tuple, pls add , or u will get interger.
print(t2)
print(type(t2))

print("------2_2------")
#What if we don't put a comma? #@@
t2_2=(1)
print(t2_2)
print(type(t2_2))

print("-------3-------")
t3=(1,2,3)
print(t3)
print(type(t3))

print("-------4-------")
t4=1,2,3
print(t4)
print(type(t4))

print("-------4_2-------")
t4='c','x','y'
print(t4)
print(type(t4))

print("-------5-------")
t5=(1,2,('a','b')) #tuple in tuple
print(t5)
print(type(t5))

print("-------6-------")
t6=("a", "b")
print(t6)
print(type(t6))

-------1-------

()

<class 'tuple'>

-------2-------

(1,)

<class 'tuple'>

------2_2------

<class 'int'>

-------3-------

(1, 2, 3)

<class 'tuple'>

-------4-------

(1, 2, 3)

<class 'tuple'>

-------4_2-------

('c', 'x', 'y')

<class 'tuple'>

-------5-------

(1, 2, ('a', 'b'))

<class 'tuple'>

-------6-------

('a', 'b')

<class 'tuple'>

1.3 Concatenating
In [12]: x=("a", "b")
y=1,2
print(x+y)
print(x*3)
print(x*2+y*3)

('a', 'b', 1, 2)

('a', 'b', 'a', 'b', 'a', 'b')

('a', 'b', 'a', 'b', 1, 2, 1, 2, 1, 2)

1.4 If we wnat to change things in tuple -> Change data type

In [13]: #mytup=1,2,3,4
#mytup[2]=-1 #TypeError: 'tuple' object does not support item assignment

mytup=1,2,3,4 #original
print(mytup)

#Change data type
mylist=list(mytup)
print(mylist)

#Change things inside
print("----------------")
mylist[2]=-2
print(mylist)

print("----------------")
mylist.append(5)
print(mylist)

print("----------------")
mylist.sort()
print(mylist)

print("----------------")
#Trun back to tuple
tupnew=tuple(mylist) #留意括號的差異
print(tupnew)

(1, 2, 3, 4)

[1, 2, 3, 4]

----------------

[1, 2, -2, 4]

----------------

[1, 2, -2, 4, 5]

----------------

[-2, 1, 2, 4, 5]

----------------

(-2, 1, 2, 4, 5)

1.5 list vs tuple Comparable


If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ and will show that bigger or
smaller is True or False.

In [14]: print([1,2]<[3,4]) #List


print((1,2)<(3,4)) #Tuple

print("-----")
print((0, 1, 2) < (5, 1, 2))
print((0, 1, 2000000) < (0, 3, 4))
print(('Jones','Sally') < ('Jones','Sam'))
print(('Jones', 'Sally') < ('Adams','Sam'))

True

True

-----

True

True

True

False

1.6 Packing and Unpacking

In [15]: #packing
family="father", "mother", "brother"
print(family)
print(type(family))

print('-------------------------------')
height=175,160,190
print(height)

print('-------------------------------')
#unpacking(lists, tuples)
f,m,b=height #因height有3個東西,我們插了三個旗子上去
print(f,m,b)


print('-------------------------------')
#改插旗子
f,m,b=b,m,f
print(f,m,b)

('father', 'mother', 'brother')

<class 'tuple'>

-------------------------------

(175, 160, 190)

-------------------------------

175 160 190

-------------------------------

190 160 175

1.7 Sorted
Original data does NOT change

In [16]: mytup=(60,3,7,1,8,20)
print(mytup)

print('--------------------')
print(sorted(mytup)) #小至大
#help(sorted) #We will get a list. #@@

print('--------------------')
print(sorted(mytup,reverse=True)) #大至小

print('--------------------')
print(tuple(reversed(mytup))) #反向印出,留意寫法

print('--------------------')
print(mytup) #以上均不改變原本的資料

print('--------------------')
#想保留改變後的樣子,另存為一個新的變數
t8=sorted(mytup)
print(t8)
print(mytup)

(60, 3, 7, 1, 8, 20)

--------------------

[1, 3, 7, 8, 20, 60]

--------------------

[60, 20, 8, 7, 3, 1]

--------------------

(20, 8, 1, 7, 3, 60)

--------------------

(60, 3, 7, 1, 8, 20)

--------------------

[1, 3, 7, 8, 20, 60]

(60, 3, 7, 1, 8, 20)

2. Dictionary {"key":value, "key":value ...}


key-value pair
not in order(no index can use)
can't change key, but can change value

2.1 Create empty dictionary

In [17]: #Method1
md=dict()
print(md)
print(type(md))

print("----")
#Method2
md1={}
print(md1)
print(type(md1))

{}

<class 'dict'>

----

{}

<class 'dict'>

2.2 Using key


Put things into dictionary
Get Value

In [18]: #Create a New Dictionary


bag={} #創造一個空的字典
bag["money"]=1000 #創造key與value,一對一對丟進去
bag["book"]=2 #創造key與value,一對一對丟進去
bag["candy"]=5 #創造key與value,一對一對丟進去
print(bag)

print("--------------------------------------")
#也可以這麼做
bag=dict() #重置一下
bag={"money":1000, "book":2, "candy":5}
print(bag)

{'money': 1000, 'book': 2, 'candy': 5}

--------------------------------------

{'money': 1000, 'book': 2, 'candy': 5}

In [19]: #Use key can get value


print(bag["book"])
print(bag["money"])

1000

In [20]: #If the key exist, the value changes


bag["money"]=2000 #本1000變2000
print(bag)

print("--------------------------------------")
bag["book"]=bag["book"]+3
#bag["book"]+=3 #@@
print(bag)

print("---------------------------------------------------")
#If the key doesn't exist, a new key-value pair is added
bag["pencil"]=5
print(bag)

print("----------------------------------------------------------------")
bag["other"]=bag["candy"]+bag["pencil"]
print(bag)

{'money': 2000, 'book': 2, 'candy': 5}

--------------------------------------

{'money': 2000, 'book': 5, 'candy': 5}

---------------------------------------------------

{'money': 2000, 'book': 5, 'candy': 5, 'pencil': 5}

----------------------------------------------------------------

{'money': 2000, 'book': 5, 'candy': 5, 'pencil': 5, 'other': 10}

In [21]: # delete pairs


del(bag["candy"]) #刪除key為'candy'的那對
print(bag)

print("----------------------------------------------------")
del(bag["other"]) #刪除key為'other'的那對
print(bag)

{'money': 2000, 'book': 5, 'pencil': 5, 'other': 10}

----------------------------------------------------

{'money': 2000, 'book': 5, 'pencil': 5}

2.3 x.keys() and x.values()


取得所有的keys
取得所有的values

In [22]: #dir(md3) #Check what we can do to dictionary

In [23]: md3={"a":1, "b":2, "c":3, "d":4, "e":5,}


print(md3.keys())
print(md3.values())

dict_keys(['a', 'b', 'c', 'd', 'e'])

dict_values([1, 2, 3, 4, 5])

2.4 x.items() and sorted()


Returns a list of (key,value) tuples
No change to original data
In [24]: md3={"a":1, "b":2, "c":3, "d":4, "e":5,}
print(md3.items()) #returns a list of tupple

print('--------------------------------------------------')
print(sorted(md3.items())) #按key小至大排序

print('--------------------------------------------------')
print(sorted(md3.items(), reverse=True)) #按key大至小排序

dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

--------------------------------------------------

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

--------------------------------------------------

[('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]

2.5 x.pop() and x.popitem()


x.pop() -> Error
x.pop("key") -> show popped value, really change the dictionary
x.popitem() -> pop the last pair amd show popped pair, really change the dictionary

In [25]: help(md3.pop) #let's see what we can get form pop



#----------------------------------------------------------------#
#If use x.pop()
#in list x.pop() -> pop the last one

#vs

#in diciotnary x.pop()
#md3.pop() -> TypeError: pop expected at least 1 argument, got 0
#----------------------------------------------------------------#

md3={"a":1, "b":2, "c":3, "d":4, "e":5,} #original

print("--------------------------------")
print(md3.pop("d"))

print("--------------------------------")
print(md3)#Really changed

Help on built-in function pop:

pop(...) method of builtins.dict instance

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

--------------------------------

--------------------------------

{'a': 1, 'b': 2, 'c': 3, 'e': 5}

In [26]: help(md3.popitem) #-> Pairs are returned in LIFO (last-in, first-out) order.

#----------------------------------------------------------------#
md3={"a":1, "b":2, "c":3, "d":4, "e":5,} #original

print('----------------------------------------------------------------')
print(md3.popitem()) #pop the last one and show it

print('----------------------------------------------------------------')
print(md3) #Really changed

Help on built-in function popitem:

popitem() method of builtins.dict instance

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order.

Raises KeyError if the dict is empty.

----------------------------------------------------------------

('e', 5)

----------------------------------------------------------------

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

2.5 In operator
Check if key is inside the dictionary

In [27]: #Check for our sample here


dic={"school":"NCCU", "phone":"0937XXXXXX", "birth":"1225"}
print(dic.keys())

print("---------------------------------------------------------------------------")
print(dic.values())

print("---------------------------------------------------------------------------")
print(dic.items()) #get tuples

print("---------------------------------------------------------------------------")
print(sorted(dic.items(), reverse=True))

print("---------------------------------------------------------------------------")
print(dic) #Nothing Changes

dict_keys(['school', 'phone', 'birth'])

---------------------------------------------------------------------------

dict_values(['NCCU', '0937XXXXXX', '1225'])

---------------------------------------------------------------------------

dict_items([('school', 'NCCU'), ('phone', '0937XXXXXX'), ('birth', '1225')])

---------------------------------------------------------------------------

[('school', 'NCCU'), ('phone', '0937XXXXXX'), ('birth', '1225')]

---------------------------------------------------------------------------

{'school': 'NCCU', 'phone': '0937XXXXXX', 'birth': '1225'}

In [28]: #add a key-value pair


dic={"school":"NCCU", "phone":"0937XXXXXX", "birth":"1225"}
dic["age"]="25"
dic["height"]="178"
print(dic)

{'school': 'NCCU', 'phone': '0937XXXXXX', 'birth': '1225', 'age': '25', 'height': '178'}

In [29]: #In operator


dic={"school":"NCCU", "phone":"0937XXXXXX", "birth":"1225"}
print("phone" in dic) #T
print("0937XXXXXX" in dic) #@@ #F
print('school' in dic) #T
print('school' not in dic) #F
print("weight" in dic) #F

True

False

True

False

False

2.6 dic["key"] and dic.get("key")


To find things in dictionary
dic["key"] -> get value, if can't find get KeyError
dic.get("key") -> get value, if can't find then nothing happens
print(dic.get("key")) -> get value, if can't find then show None

In [30]: # Let's check again our example


print(dic)
# {'school': 'NCCU', 'phone': '0937XXXXXX', 'birth': '1225', 'age': '25', 'height': '178'}

print('----------------------------------------------------------------------------------------')
#dic["weight"] # KeyError: 'weight'
print(dic["school"])

#vs

print('----------------------------------------------------------------------------------------')
print(dic.get("weight"))
print(dic.get("school"))

#vs next cell

{'school': 'NCCU', 'phone': '0937XXXXXX', 'birth': '1225'}

----------------------------------------------------------------------------------------

NCCU

----------------------------------------------------------------------------------------

None

NCCU

In [31]: dic.get("weight") #nothing happens



#vs next cell

In [32]: #如找不到就顯示None
dic.get("weight", "None")

#vs next cell

Out[32]: 'None'

In [33]: #有找到就顯示找到的東西
dic.get("phone", "None")

Out[33]: '0937XXXXXX'

2.7 loops in dictionary


In [34]: # Let's check again our example
print(dic)
# {'school': 'NCCU', 'phone': '0937XXXXXX', 'birth': '1225', 'age': '25', 'height': '178'}

print('----------------------------------------------------------------------------------------')
for i in dic:
print(i) #i = key 不再是index了

print('----------------------------------------------------------------------------------------')
#To get key and values
#Method1
for i in dic:
print(i, dic[i]) #i = key 不再是index了

print('----------------------------------------------------------------------------------------')
#Method2
print(dic.items()) #Let's check how it looks like
for k,v in dic.items():
print(k,v)

{'school': 'NCCU', 'phone': '0937XXXXXX', 'birth': '1225'}

----------------------------------------------------------------------------------------

school

phone

birth

----------------------------------------------------------------------------------------

school NCCU

phone 0937XXXXXX

birth 1225

----------------------------------------------------------------------------------------

dict_items([('school', 'NCCU'), ('phone', '0937XXXXXX'), ('birth', '1225')])

school NCCU

phone 0937XXXXXX

birth 1225

In [35]: #To sort by key


for k,v in sorted(dic.items()):
print(k,v)

print('----------------')
#To sort by key and want reverse
for k,v in sorted(dic.items(), reverse=True):
print(k,v)

print('----------------')
#Even we change the order in print, it still sort by key
for k,v in sorted(dic.items()):
print(v,k)

birth 1225

phone 0937XXXXXX

school NCCU

----------------

school NCCU

phone 0937XXXXXX

birth 1225

----------------

1225 birth

0937XXXXXX phone

NCCU school

In [36]: #How to sort based on the value, not the key?


listA=list()
for k,v in dic.items():
listA.append((v,k)) #把Vlaue放在前面
print(listA)

print('--------------------------------------------------------------------------------------------------')
a1=sorted(listA) #由小至大
print(a1)

print('--------------------------------------------------------------------------------------------------')
b1=sorted(listA, reverse=True) #由大至小
print(b1)

#Why not 合在一起? 因純印print(listA.append((v,k)))會發現他是None,所以無法對None做排序,就會產生Error

[('NCCU', 'school'), ('0937XXXXXX', 'phone'), ('1225', 'birth')]

--------------------------------------------------------------------------------------------------

[('0937XXXXXX', 'phone'), ('1225', 'birth'), ('NCCU', 'school')]

--------------------------------------------------------------------------------------------------

[('NCCU', 'school'), ('1225', 'birth'), ('0937XXXXXX', 'phone')]

In [37]: #practice again


md={"c":2, "a":4, "b":22} #pls note key not in order
print(md.items())

print('-------------------------------------------')
for i in md:
print(i, md[i])

print('-------------------------------------------')
for k,v in md.items():
print(k,v)

print('-------------------------------------------')
for k,v in sorted(md.items()): #pls note key is in order now
print(k,v)

print('-------------------------------------------')
for k,v in sorted(md.items(), reverse=True):
print(k,v)

print('-------------------------------------------')
for k,v in sorted(md.items()): #pls note key is in order now
print(v,k)

dict_items([('c', 2), ('a', 4), ('b', 22)])

-------------------------------------------

c 2

a 4

b 22

-------------------------------------------

c 2

a 4

b 22

-------------------------------------------

a 4

b 22

c 2

-------------------------------------------

c 2

b 22

a 4

-------------------------------------------

4 a

22 b

2 c

In [38]: #Try to sort by value


lst=[]
for k,v in md.items():
lst.append((v,k))
print(lst)

print('-------------------------------')
print(sorted(lst))

print('-------------------------------')
print(sorted(lst, reverse=True))

[(2, 'c'), (4, 'a'), (22, 'b')]

-------------------------------

[(2, 'c'), (4, 'a'), (22, 'b')]

-------------------------------

[(22, 'b'), (4, 'a'), (2, 'c')]

3. Common Sequence Operations

3.1 in operater

In [39]: mystr="Taiwan"
mylist=[1,1,2,3]

print("T" in mystr)
print("an" in mystr)
print(1 in mylist)
print("t" in mystr)
print("T" not in mystr)
print(3 not in mylist)
print(3 in mylist)

True

True

True

False

False

False

True

3.2 +, * operator

In [40]: print(mystr+" "+mystr)


print(mystr+mystr)
print(mylist+mylist)
print((mystr+" ")*3)
print(mylist*3)

Taiwan Taiwan

TaiwanTaiwan

[1, 1, 2, 3, 1, 1, 2, 3]

Taiwan Taiwan Taiwan

[1, 1, 2, 3, 1, 1, 2, 3, 1, 1, 2, 3]

3.3 len(x), min(), max(), x.count(value)


In [41]: print(len(mylist))
print(len(mystr))
print(min(mystr))
print(max(mystr))
print(min(mylist))
print(max(mylist))
print(mystr.count("a"))
print(mylist.count(1))

End of Class

You might also like