1 / 33

Introduction to Python

Introduction to Python. Aug 22, 2013 Hee -gook Jun. Outline. Introduction Data structure List Set Tuple Dictionary Miscellaneous. Installation. Linux (already installed) Google Chrome Extension https:// chrome.google.com/webstore/detail/python-shell/gdiimmpmdoofmahingpgabiikimjgcia

shima
Download Presentation

Introduction to Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Python Aug 22, 2013 Hee-gook Jun

  2. Outline • Introduction • Data structure • List • Set • Tuple • Dictionary • Miscellaneous

  3. 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. Python Integrated Development Environment(IDE) • PyScripter • https://code.google.com/p/pyscripter • Download the setup file and excute

  5. Outline • Introduction • Data structure • List • Set • Tuple • Dictionary • Miscellaneous

  6. 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. 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. 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. 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. 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. List: sort [5/8] myList = [1,7,4,2] sorted(myList) myList myList.sort() myList myList.reverse() myList

  12. List: sort by Key [6/8] # use first and third value of tuple as a key defCustomKey(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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Dictionary: when to use dictionary [5/5] When you need, • A logical association between a key:valuepair • Fast lookup for data, based on a custom key • To be modifying data constantly

  27. Outline • Introduction • Data structure • List • Set • Tuple • Dictionary • Miscellaneous

  28. 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. 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. 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. 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. 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. 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)용으로만 쓰이기 때문

More Related