Download presentation
Presentation is loading. Please wait.
Published byReynold Richards Modified over 9 years ago
1
Introduction to Python Aug 22, 2013 Hee-gook Jun
2
2 / 33 Outline Introduction Data structure – List – Set – Tuple – Dictionary Miscellaneous
3
3 / 33 Installation Linux (already installed) Google Chrome Extension – https://chrome.google.com/webstore/detail/python- shell/gdiimmpmdoofmahingpgabiikimjgcia Windows – www.python.org > DOWNLOAD > “Python 3.X” or “Python 2.X” – 제어판 > 시스템 및 보안 > 시스템 > 고급 시스템 설정 > 환경변수 > Path > ;C:\Python33 (or Python27) 경로 추가
4
4 / 33 Python Integrated Development Environment(IDE) PyScripter – https://code.google.com/p/pyscripter – Download the setup file and excute
5
5 / 33 Outline Introduction Data structure – List – Set – Tuple – Dictionary Miscellaneous
6
6 / 33 Data structure List [a,b,c,..] – List of mutable values – Unordered collection Set {1,2,3,..} – Unordered collection – Do not contain duplicate values like the one in math Tuple (1,2,3,..) – List of immutable(constant) values Dictionary {“key”:”value” … } – Map(Hash)-like data structure – [key, value]
7
7 / 33 List [1/8] myList = [] # Make an empty list type(myList) # Get type of the given data myList = [1, 1.0+3j, “apple”, True] # Make a list containing four entities myList = [1,2,3,4,5] myList[0] # Get the first element from the list myList[1:4] # Get a list containing elements 1, 2 and 3 (under 4) from the list myList[1:len(myList)] # Get a list from the second to the last element in the list myList[-2] # Get the second element from the end of the list
8
8 / 33 List: addition [2/8] myList = [1,2,3,4] myList[2] = 1.0 + 2j # modify an element myList.append("test") # Add an element to the end of the list myList.insert(3, "third") # Add an element at the specific index in the list myList.extend(['a', 'b', 'c']) # Add elements myList += ['third'] myList += 'third' # difference between append and extend tmp = [1,2,3,4] tmp.append([5,6,7]) tmp.extend([5,6,7])
9
9 / 33 List: position [3/8] len(myList) # size of the list myList.count('third') myList.index('third') myList.index('third', 3) myList.index('third', 3, 10) myList.index('third', 3, 5) myList.index('d') myList.index('d', 1, len(t)) myList.index('d', 1, len(t)-1)
10
10 / 33 List: pop and remove [4/8] myList.pop() # pop the last element in the list myList.pop(1) # pop an element at the specified position in the list myList.count('third') myList.remove('third') myList myList.remove('third') myList del(myList[2]) # Remove the second element from the list
11
11 / 33 List: sort [5/8] myList = [1,7,4,2] sorted(myList) myList myList.sort() myList myList.reverse() myList
12
12 / 33 List: sort by Key [6/8] # use first and third value of tuple as a key def CustomKey(x): return (x[0], x[2]) myList=[(1,1,'z'),(1,2,'a'),(1,2,'c'),(2,2,'b'),(2,2,'c')] myList.sort(key=CustomKey) myList myList.sort(key=CustomKey, reverse=True) myList myList.sort(key=lambda x: (x[0], x[2])) # utilization of lambda function myList.sort(key=lambda x: (x[0], x[2]), reverse=True)
13
13 / 33 List: copy [7/8] myList = [1,7,4,2] tmpList1 = myList[:] # deep copy (for list data type) import copy tmpList2 = copy.deepcopy(myList) # deep copy (for any type) tmpList3 = myList # swallow copy tmpList1.sort() tmpList1 myList tmpList2.sort() tmpList1 myList tmpList3.sort() tmpList2 myList
14
14 / 33 List: when to use lists [8/8] When you need a, Mixed collection of data all in one place Data that needs to be ordered Data that requires the ability to be changed or extended – lists are mutable Do not require data to be indexed by a custom value – Lists are numerically indexed and to retrieve an element (like array) Stack or Queue – Lists can be easily manipulated by appending/removing elements from the beginning/end of the list Data doesn’t have to be unique
15
15 / 33 Set (only stores unique things) [1/5] s = set() s = set([1,1,2,3,4,]) r = set([1,2, 'apple']) s.union(r) s.intersection(r) s = set([1,2,3]) f = frozenset([1,2,3]) # just like a regular set, except that is immutable s[0] = 9 f[0] = 9
16
16 / 33 Set: addition [2/5] s = set([1,1,2,3,4,]) s.add(5) # difference between add and update (remind append and extend of the list) s = set([1,2,3,4]) tmp.add([5,6,7]) tmp.update([5,6,7])
17
17 / 33 Set: pop and remove [3/5] s = {'a', 2, 3} s.pop() # pop the last element in the set s.pop(1) # pop() takes no arguments for the set s.remove('a') len(s)
18
18 / 33 Set: operations [4/5] a = {1,2,3} b = {3,4,5} type(a) a | b # a.union(b) a & b # a.intersection(b) a – b # difference a ^ B # symmetric difference
19
19 / 33 Set: when to use sets [5/5] When you need a, Unique set of data – Sets check the unicity of elements based on hashes Constantly changing data – Sets, just like lists, are mutable Collection that can be manipulated mathematically – With sets it’s easy to do operations like difference, union, intersection, etc Do not store nested lists, sets, or dictionaries in a data structure – Sets don’t support unhashable types. – s = { 1, [1,2], {1,2}, (1,2), 'a' }
20
20 / 33 Tuple: a list you can’t change [1/2] # Tuple has a great performance because of their immutability # Python will know exactly how much memory to allocate for the data to be stored t = (1, 2, 3) t = 'a', 'b', 'c' t[0] = 9 # Tuples are immutable t = 'a', 'b', [1,2,3] # However, it can hold mutable objects oneT = 'a' type(oneT) # string oneT = 'a', # tuple with one element requires a trailing comma oneT = ('a', ) type(oneT)
21
21 / 33 Tuple: when to use tuples [2/2] When you need to, Store data that doesn’t have to change Get a higher performance of the application – In this situation you can use tuples whenever you have fixed data collections Store your data in logical immutable pairs, triples etc
22
22 / 33 Dictionary: “key:value” pair [1/5] d={1:'a', 2:'b', 3:3} # numeric values as keys d={'a':'a', 'b':'b', 'c':3} # string values as keys d={"first":'a', 'second':2, 3:'c'} # string or numeric values as keys d = dict( [ (1, 'a'), (2:'b'), (3:'c') ] ) # numeric values as keys d = dict(a=1, b=2, c=3) # string values as keys d = dict(a='aa', b='bb', c='cc') d = dict(a=aa, b=bb, c=cc) d = dict( [ (1, 'a'), (2:'b'), (3:'c') ], a=2, b=3 ) # numeric or string values as keys d = { x:x*x for x in (1,2,3)}
23
23 / 33 Dictionary: add and remove [2/5] d={'a':1,'b':2,'c':3,'d':4} d['e'] = 5 d[6] = 6 d['list'] = [1,2,3] del d['a'] d.clear()
24
24 / 33 Dictionaries: retrieval of value [3/5] d={1:'a', 2:'e', 3:'I', 4:'o', 5:'u'} d[1] # 1 is not an index! 1 is a key! d[len(d)] d={'a':1,'b':2,'c':3,'d':4} d[1] d["a"]='aa'
25
25 / 33 Dictionary: “key:value” pair [4/5] d={'a':1,'b':2,'c':3,'d':4} for i in d.items(): print(i) for k, v in d.items(): print(k,v) for k in d.keys(): print(k) for v in d.values(): print(v)
26
26 / 33 Dictionary: when to use dictionary [5/5] When you need, A logical association between a key:value pair Fast lookup for data, based on a custom key To be modifying data constantly
27
27 / 33 Outline Introduction Data structure – List – Set – Tuple – Dictionary Miscellaneous
28
28 / 33 declaration for an empty test = [] # by literal syntax test = list() # by list() method # No literal syntax for the empty set! test = set() test = () test = tuple() test = {} test = dict()
29
29 / 33 converting type a = set((1,2,3)) type(a) b = list(a) type(b) c = tuple(b) type(c) d = set(c) type(d)
30
30 / 33 Check existence a = set((1,2,3)) 1 in a b = list(a) 2 in b c = tuple(b) 3 in c d={'a':1,'b':2,'c':3,'d':4} ‘a’ in d # check existence of key
31
31 / 33 Efficiency of Tuples # Multiple assignment a, b, c = 3, 4, 5 # Swapping without a temp variable (x,y) = (1,2) x,y = y,x # Tuples are used internally in Python in a lot of places # dictionaries cannot use a list as a key, but they can use a tuple d = {} d[ (1,2) ] = 'aa' # Set tuple as a key d[ [3,4] ] = 'bb' # Cannot set list as a key
32
32 / 33 List of list table = list() list1 = ['a', '1', '1|1|1'] list2 = ['b', '2', '2|2|2'] list3 = ['c', '3', '3|3|3'] table.append(list1) table.append(list2) table.append(list3) print(table)
33
33 / 33 2D Array # Array b=[0 for i in range(5)] # 2D Array b= [ [0 for i in range(4)] for j in range(5) ] b= [[0]*4 for i in range(5)] # 여기서 굳이 b=[[0 for i in xrange(4)] for i in xrange(5)] 라고 하지 않아도 되는 이유는 # 0 이 immutable 일 뿐 아니라 # 어차피 여기에서는 그 내용에 상관없이 # 자리 채우기 (place holder) 용으로만 쓰이기 때문
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.